Pages

Tuesday, July 17, 2012

java singleton, when you want to avoid multiple instances but one.

Singleton is a creational design pattern used to prevent from creating duplicate objects from a certain class. That is it limits the class to create only one object. Below example shows how to do this.

static Object o;

public static Object getObject(){

        if(o==null)
           o= new Object();

      return o;
}

This is actually a specialization of java's static factory method design pattern.

No comments:

Post a Comment