Showing posts with label Design Patterns. Show all posts
Showing posts with label Design Patterns. Show all posts

Wednesday, January 29, 2014

Static factory methods vs Factory pattern

Many of us are familiar with the use of static factory methods for object creation. However, there is quite a bit of confusion as to whether such static factory methods are the same as the factory pattern. Let me attempt to explain the difference between the two here.

Static factory method
A static factory method also known as named constructor is employed either in place of or in addition to traditional constructors for creating objects of the class. 

The advantages of using static factory methods are:

  1. Meaningful names for constructors
  2. Choice of creating new object or returning existing one (Ex: used in singletons)
  3. Can return sub-class objects

Now, static factory method has nothing to do with the Factory pattern. In case of factory pattern, one or more factory methods are defined in a factory class and are used to create objects of multiple possibly unrelated types.

Factory pattern

This pattern hides the object creation logic while providing a well defined interface for object creation.



Friday, January 17, 2014

Double checked locking optimization

Double checked locking aims to improve performance by reducing the need to acquire a lock by checking for the locking criteria first without acquiring the lock. Subsequently, if the lock is acquired, the locking criteria is checked again in order to ensure thread-safe code.

The locking criterion variable needs to be volatile for this to work correctly. If it not volatile, the compiler might optimize access to the variable thus allowing for it to contain an older value when the locking criterion check is made.

This technique is generally used in Singleton definition.

Example
public final class MySingleton implements Cloneable {
  private static volatile MySingleton instance = null;  
  
  private MySingleton() {
  }

  public static MySingleton getInstance() {
     if (instance == null) {
         synchronized(this) {               
               if (instance == null) {
                   instance = new MySingleton();
               }   
           }
     }
      return instance;
  }  
}

Wednesday, January 15, 2014

Singletons in Java

As developers, we all have heard of Singletons. It would not be an exaggeration to state that it is the most popular design pattern. Having said that, what exactly is a Singleton?

A class that can only be instantiated only once is referred to as a Singleton.

In order to design a Singleton class, the following rules should be adopted:
  • Private constructors
    • This prevents creating objects of the class at will and ensures that object creation can only be done by code inside the class
    • It also prevents sub-classing
  • Class should be final
    • This prevents sub-classing
    • It also makes it explicit to the developer that the class cannot be sub-classed
  • Private static Object reference 
    • This is to store the reference to the singleton
    • Should be static
    • Should be private
    • Should be volatile
  • Static method that returns the singleton reference
    • Should be static
    • Should be public
    • Should be synchronized. This is to ensure that the method is thread-safe and a single object is created even in multi-threaded scenarios
    • Create object if not created
    • Return object reference
  • Prevent cloning
    • Implement Cloneable interface and throw the CloneNotSupportedException
    • This prevents cloning of the singleton

Example 1:
public final class MySingleton implements Cloneable {
  private static volatile MySingleton instance = null;
  
  private MySingleton() {
  }

  public static synchronized MySingleton getInstance() {
      if (instance == null) {
          instance = new MySingleton();
      }
      return instance;
  }  

  protected Object clone() throws CloneNotSupportedException {
      throw new CloneNotSupportedException();
  }
}

Approach II
Another approach is to create and assign the object to the static reference variable in the definition itself. Since, static members are initialized only once during class loading, it obviates the need to serialize calls to the static method which returns the singleton.

Example 2:
public final class MySingleton {
  private static MySingleton instance = new MySingleton();
  
  private MySingleton() {
  }

  public static MySingleton getInstance() {
      return instance;
  }  

  protected Object clone() throws CloneNotSupportedException {
      throw new CloneNotSupportedException();
  }
}

References
http://www.javaworld.com/article/2073352/core-java/simply-singleton.html