• Post Reply Bookmark Topic Watch Topic
  • New Topic

Call Singleton From A Factory, Or Just Use Singleton  RSS feed

 
Sam Gehouse
Ranch Hand
Posts: 281
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am debating on whether to just use Singleton, or call Singleton from Factory. I definitely need Singleton. Do I have any real need for calling Singleton instances from a factory?

I am showing the code example below:

public class MyProvider {
private static accountManager accountManager;
private static specimenManager specimenManager;
private static accountBroker accountBroker;

// Whole method is synchronization to prevent two calls of the method.
public static synchronized AccountManager getAccountManager() {
// Lazy initialization
if (mgr ==null) {
mgr = new AccountManager ();
}
return mgr;
}

public static synchronized SpecimenManager getSpecimenManager() {
.....code goes here as above....
}

public static synchronized AccountBroker getAccountBroker() {
.....code goes here as above....
}
}

This is the dilemma I am having.
1) Do I have a need to synchronize the whole getX() method for defensive coding?
2) Do I have a need to call Singleton from a separate factory?
3) MyProvider class itself is not a Singleton.

Thanks in advance.
Sam
SCJP, SCWCD
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Getting a singleton from a factory lets you work around one of the more serious problems with singleton which is they can be darned hard to extend or replace. You make a factory method with a return type that is an interface and have flexibility in exactly what class you return. I have a small app with a single DataStore, but I can choose MemoryDataStore or FileSystemDataStore in configuration. No code outside the DataStore package even knows I have two implementations.

Yes, lazy instantiation has to be synchronized as you showed it. Sun used to promote a locking technique and then a double locking technique and they flat did not work in tricky threading or multi-processor machines.

Your factory seems to be all static which is a viable way to do it. But now the factory is hard to extend or replace! You can go bananas - make your factory create an instance of some other class to do the work for it - and never completely eliminate such problems. Worst case: the factory becomes be a site of change that you didn't really want to change. Just be aware when it happens.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!