Singleton and Factory Design Patterns: Java Implementation

Overview

This is actually a learning notes for design patterns of Singleton and Factory Design patterns and use Java to do the implementation.

What is Design Pattern

To me, the concept of design pattern is to describe the template of a real design which consists of useful experience and thus keep the code as maintainable, reusable, extendable as possible.

Factory Design Pattern

Actually it is simple, it just put all of the initialization work into a single place called XFactory with the two main advantages:

  • creates objects without exposing the instantiation logic to the client.
  • refers to the newly created object through a common interface

The best advantage brought by Factory Design pattern is that whenever the requirements about how to create objects change, we only need to change the factory class, rather than modify code here and there. (e.g., a new type of object is added later on) The factory class usually inolves the following simple sturcture

public class ProductFactory{
	public Product createProduct(String ProductID){
		if (id==ID1)
			return new OneProduct();
		if (id==ID2) return
			return new AnotherProduct();
		... // so on for the other Ids

        return null; //if the id doesn't have any of the expected values
    }
    ...
}

Sample factory is like the DB connection pool, thread pool and so on

Singleton Pattern

After applying singleton pattern, only one instance of the class A can be created. So the key actually is how to forbidden the creation of the object once the first object is already created:

  1. The constructor has to be declared as private: otherwise, the client can easily create as many objects as it wants by new A()
  2. Consider multiple threaded execution environment

So an efficient way would be using doubly checking lock implementation and the explanation is included along with the code comment:

public class SingletonDemo {
    private static volatile SingletonDemo instance = null;
    /*
     * Declaring a volatile Java variable means: The value of this variable
     * will never be cached thread-locally: all reads and writes will go straight
     * to "main memory"; Access to the variable acts as though it is enclosed in
     * a synchronized block, synchronized on itself.
    */

    private SingletonDemo() { }

    public static SingletonDemo getInstance() {
        if (instance == null) {
        // improve efficiency so all the threads after the first creation of
        // the instance will not try to create a lock which is resources consuming

            synchronized (SingletonDemo.class) {
                // so over the whole class range/level, it is guaranteed that
                // there would only a single thread allowed to execute the following code
                if (instance == null) {
                    instance = new SingletonDemo();
                }
            }
        }

        return instance;
    }
}

Summary

This is actually a learning notes for design patterns of Singleton and Factory Design patterns and use Java to do the implementation.

Written on January 27, 2015