I had read article about singleton in Action last week. It told about how bad singleton is and why don’t use it with a little example in another site. It told singleton isn’t different from static method and it gives another responsibility to object. Oh, why they think about it like this. I think singleton isn’t bad like it say and as I see in example from site that article link to. It just use in wrong place.
Singleton is created for ensure system has only one instance all time. It’s not create for replace static class. When you want to use singleton, you still want object that has method not use class to call. Ok see the example that site show how bad about singleton.
testCreditCardCharge() {
Database.init();
OfflineQueue.init();
CreditCardProcessor.init();
CreditCard c = new CreditCard(
"1234 5678 9012 3456", 5, 2008);
c.charge(100);
}
Are you see what’s wrong in the example? Hey, where’s singleton object? All I see is class not object. Ok, look in their solution.
testCreditCardCharge() {
Database db = new Database();
OfflineQueue q = new OfflineQueue(db);
CreditCardProcessor ccp = new CreditCardProcessor(q);
CreditCard c = new CreditCard(
"1234 5678 9012 3456", 5, 2008);
c.charge(ccp, 100);
}
Oh, they change from class to new object but if they want to use singleton why they don’t write like this.
testCreditCardCharge() {
Database db = Database.get();
OfflineQueue q = new OfflineQueue(db);
CreditCardProcessor ccp = new CreditCardProcessor(q);
CreditCard c = new CreditCard ...
}
I think singleton is like factory method but instead of create many instance it create only once and return that instance alway when someone call create from it. It’s used for reduce overhead when create object and use memory more efficiency. So, it’s not bad like the example, it should use for create object. However, for some reasons, many use it for replaced static method and that why it looks so bad.