How Do You Combine Abstract Factory with Singleton Pattern? [Closed]
I Am Coding in Java and Am New with These Patterns. Can Anyone Give Me an Example of a Factory Abstract Also Using Singleton? 1 2 Answers Here's an Example of...
I am coding in java and am new with these patterns. Can anyone give me an example of a factory abstract also using singleton?
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();
}
// ...
}
Factory 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