Archive

Archive for January, 2009

Singleton Pattern In Java

January 22nd, 2009

Singleton pattern is probably one of most popular widely used patterns that I have seen. It’s implemented to create an access restriction to a specific resource like: printer, network, pooling, memory, logging.

Here is a simple and correct implementation:

public class Singleton implements Serializable{
	private static Singleton _INSTANCE = null;

	static{
  		_INSTANCE = new Singleton();
 	}

	private Singleton() {
  	}

	public static Singleton getInstance() {
		return _INSTANCE;
	}
 }

Lets look at one by one.

private static Singleton  _INSTANCE keeps reference of the instance
static block this will prevent multi-thread initialization
readResolve() to make sure a new instance is not created by deserialization process

Beware that double locking solution will not work:

class Singleton {
  private static  Singleton singleton = null;
  public static Singleton getSingleton() {
    if (singleton == null){
        synchronized(this) {
           if (singleton == null)
              singleton = new Singleton ();
        }
   }
    return singleton ;
    }
  }

Please read the article why.

Java

Understanding Dynamic Proxies

January 11th, 2009

Dynamic proxies have existed since J2SE 1.3 and have been mainly utilized as a mechanism for method interception so that additional behavior could be interposed between a class caller and its callee. Dynamic proxies exemplify AOP (Aspect Oriented Programming) which bundled within Spring Framework API, it provides alternative for implementing common design patterns like Façade, Bridge, Decorator, Proxy.

Read more…

Java , , ,