Singleton Factory : Singleton « Design Pattern « Java Tutorial






class Product {
}

interface Factory {
  Product create();
}

class SingletonFactory implements Factory {
  private Product product;

  public synchronized Product create() {
    if (this.product == null) {
      product = new Product();
    }
    return product;
  }
}

public class FactoryDemo {

  public static void main(String[] args) {
    Factory factory = new SingletonFactory();
    Product p1 = factory.create();
    for (int i = 0; i < 100; i++) {
      if (factory.create() != p1) {
        System.out.println("Factory returned another instance of Product!");
      }
    }
  }

}








34.1.Singleton
34.1.1.Basic Singleton
34.1.2.The Singleton design pattern: you can never instantiate more than one.
34.1.3.Singleton test
34.1.4.Synchronized Singleton
34.1.5.Singleton Factory