An alternative to the Singleton pattern?
I'm trying to design a more flexible form of Singleton.
The problems I'm trying to address are the following:
Now, the solution I came up with so far is the following:
SingletonShared
class that will be passed as a parameter to the Singleton's constructor. Those two are hidden behind a public SingletonFactory
, that has the static method getInstance(key)
. setAdapter(adapter)
to the SingletonFactory
. Using the method getShared(key)
, a class that implements ISingletonAdapter
should return the SingletonShared
value of that instance (eg, SingletonXmlAdapter
is passed an Xml file to the constructor, and deserializes a certain node based on the key it was given). All of the above are packed as a Singleton
package.
Now, for test-ability purposes, there is an option of marking Singleton as an internal class and have it implement an ISingleton
public interface.
Questions:
Thanks!
I think the solution you are describing as the SingletonFactory
is the ServiceLocator pattern and your Singletons are services.
Is this solution acceptable?
It depends on how and where you use the Singletons. Singletons are not bad in themselves, so long as you isolate the code that depends on them. Otherwise you end up injecting a bunch of complex Singletons every time you need a test fixture.
If you instantiate Singletons rather than using static getters/setters it will be more difficult to dependency inject without using a DI framework, unless you pass you singletons in, but then you can end up with a long list of parameters.
Is there a better / cleaner / shorter way of achieving the same effect?
IoC containers and DI frameworks (subtlety different) are often used to control dependencies that would otherwise be Singletons. However even if you eliminate the evils of Singletons, it is still good practice to try to isolate areas of dependency on particular services.
链接地址: http://www.djcxy.com/p/51100.html上一篇: 为什么单身人士班应该被封闭?
下一篇: Singleton模式的替代方法?