I have some class it is a singleton we have this class in already several applications and it is used there as a singleton.
Now i am writing some new application and i need several instances of that class , what is a best practice to have sevaral instances of it ?
By deriving from开发者_开发技巧 it and making the private constructur to be public, I work with c# ?
Or there can be someother idea here ?
Thanks
Simple: don't make it a singleton. The word 'single' is there for a reason.
There is supposed to be only one Singleton. If you have more than one, it's not a Singleton.
Maybe a Multiton is what you want?
It would seem to me that if you need several instances of this class, then you would handle it like any other and you would remove anything in the class that forces it to be a singleton, which then it would simply cease to be a singleton.
You might consider a factory class that is configurable to always return the same instance or give you different instances based on configuration or other criteria.
It really depends on how exactly is the class implemented as a singleton.
If the class has a private default constructor and the singleton instance is create through a static factory method, your only option is to derive from the class (as long as it's not sealed) and provide a public constructor on the derived class to create multiple instances.
If the class has a public constructor, and the singleton usage is just a guidance, but not enforced, you can just create as many instances as you have.
Note however, that if the class was designed as a singleton, it's quite likely that its implementation makes that assumption internally, so having multiple instances might have unexpected side effects. You should really ensure that the class is implemented so that is allows such usage scenario.
A singleton is a design pattern which provides you two guarantees:
- that exactly one instance of the class will exist, and
- that this instance is globally accessible.
If you remove the first requirement, what you have is no longer a singleton. It is a plain, old-fashioned global.
So call it by its real name. What you need is a simple global variable. You can wrap it in some kind of lazy initialization logic if you need it, but it's a global, not a singleton.
Apart from this, Singletons are a really really bad idea. Don't use them in the first place.
What you're asking for is very contradictory--could you define what you mean by Singleton to make sure we're not using different vocabulary?
If the existing object is a true static singleton then you likely won't be able to instantiate multiple instances; in order to do so you would need to load each instance (and it's callers) in their own AppDomain
which is not trivial and would be a terribly large tradeoff/hack just to get multiple Singletons.
精彩评论