Let\'s face it. The Singleton Pattern is highly controversial topic with hordes programmers on both sides of the fence. There are those who feel like the Singleto
The finest solution I have came across is using the factory pattern to construct instances of your classes. Using the pattern, you can assure that there is only one instance of a class that is shared among the objects that use it.
I though it would be complicated to manage, but after reading this blog post "Where Have All the Singletons Gone?", it seems so natural. And as an aside, it helps a lot with isolating your unit tests.
In summary, what you need to do? Whenever an object depends on another, it will receive an instance of it only through its constructor (no new keyword in your class).
class NeedyClass {
private ExSingletonClass exSingleton;
public NeedyClass(ExSingletonClass exSingleton){
this.exSingleton = exSingleton;
}
// Here goes some code that uses the exSingleton object
}
And then, the factory.
class FactoryOfNeedy {
private ExSingletonClass exSingleton;
public FactoryOfNeedy() {
this.exSingleton = new ExSingletonClass();
}
public NeedyClass buildNeedy() {
return new NeedyClass(this.exSingleton);
}
}
As you will instantiate your factory only once, there will be a single instantiation of exSingleton. Every time you call buildNeedy, the new instance of NeedyClass will be bundled with exSingleton.
I hope this helps. Please point out any mistakes.