The singleton / factory method that you describe is functional and easy to implement. But singles are dangerous, because if you want to implement the options of your services to work with you on the road, you may have to reorganize everything to accommodate them. In addition, singletones are usually transmitted with static factories, which in themselves can inhibit extensibility.
Instead of a singleton / factorial approach, consider dependency injection. This is more cumbersome to implement, but extends more gracefully.
When you implement dependencies, you expect the component needs for data / services, passing them to the dependent components before they need them. (While the alternative leaves the job of detecting data / services for this component — functionality that you could achieve with something like a static factory.) In general, you deactivate components and isolate their functionality; This is generally accepted as an effective development approach.
As a more specific example, instead of your servlets calling com.me.Herusitic#getInstance() , a Heuristic instance will be passed in their place for their constructors. This Heuristic reference is stored inside the object and is called as needed. Later, when you extended Heuristic to FancyHeuristic and FakeHeuristicForTesting , and you want your servlets to use them instead, you don’t need to change the servlet code: just switch to a new type of heuristic. With the factory approach, you have to rewrite the logic of the factory.
This answer only scratches the surface of this topic. Fortunately, there is no end to the discussion of the DI design pattern (both in StackOverflow and elsewhere), so I will leave it to continue the research.
source share