Thursday, November 04, 2004

Singletons with needles and thread

Some more....
Singletons with needles and thread: "The singleton factory
The singleton factory creates the singleton instance and guarantees that there will be only one instance in the system at any given time.

Here's an implementation of a factory that will return the LogImpl:


public abstract class AbstractLogFactory {

private static AbstractLogFactory factory = new SystemLogFactory();

public static AbstractLogFactory getFactory() {
return factory;
}

public abstract LogSingleton log();

}

class SystemLogFactory extends AbstractLogFactory {

private static LogSingleton log = new LogImpl();

public LogSingleton log() {
return log;
}
}

If you program your objects to retrieve a factory only from the AbstractLogFactory, you can switch logs without changing the classes that use the factory. When a new log you wish to use comes along, simply create a subclass of AbstractLogFactory that instantiates the proper type of log and update AbstractLogFactory to return the proper factory type.

Thus, if you would rather return a FileLog, you could make the following changes:


public abstract class AbstractLogFactory {

private static AbstractLogFactory factory = new FileLogFactory();

public static AbstractLogFactory getFactory() {
return factory;
}

public abstract LogSingleton log();

}

class FileLogFactory extends AbstractLogFactory {

private static LogSingleton log = new FactoryLog ();

public LogSingleton log() {
return log;
}

}

This alternate approach to singleton creation proves more flexible than other approaches because you move the Singleton-pattern enforcement responsibility from the implementation and to another object. In fact, this approach's flexibility lets you change from returning a singleton to creating and returning multiple instances -- all without the rest of your program knowing."

0 Comments:

Post a Comment

<< Home