I am coding in java and am new with these patterns. Can anyone give me an example of a factory abstract also using singleton?
12 Answers
Here's an example of a class implementing the singleton pattern. This implementation is also thread safe. It uses double-checked locking in order to only synchronize when needed.
public class Singleton { private volatile static Singleton instance; // Note volatile keyword. private Singleton() {} public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } } You can add any (factory) methods as members of the class Singleton. These methods will become available when you get the unique instance.
public class Singleton { /* ... */ /* Singleton implementation */ /* ... */ public MyObject createMyObject() { // Factory method. return new MyObject(); } // ... } 3Factory pattern is creational pattern used to create objects. Singleton ensures that only one instance of a class is available per JVM. Combining these two patterns would involve using AbstractFactory to create a singleton instance which means the same instance will be returned by Factory. Other answers have provided code