2

I am coding in java and am new with these patterns. Can anyone give me an example of a factory abstract also using singleton?

user3014818
  • 39
  • 1
  • 2

2 Answers2

3

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

    // ...
}
Snps
  • 13,516
  • 6
  • 49
  • 72
  • 1
    Note the keyword "volatile" is required for this approach to work. If possible it's suggested to initialize the variable statically to ensure thread safety and only one copy. private static final Singleton instance = new Singleton() for example – JustinKSU Nov 20 '13 at 20:35
  • @JustinKSU If one knows that the application will always create the singleton instance, then you can initialize `instance` statically. In my example the instance will only be created when needed (lazy creation). This might save some unnecessary creation overhead. – Snps Nov 20 '13 at 20:38
  • Agreed. However, often I see the overhead of lazy initialization when it is not necessary. The single will not be created until the Class is referenced which is generally the time you want the variable initialized anyway. The main point of my comment was to call out the "volatile" word. Many times I see 'double-checked locking' without the keyword. – JustinKSU Nov 20 '13 at 20:56
0

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

user1339772
  • 763
  • 4
  • 19