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

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();
    }

    // ...
}
3

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

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest