Thursday, April 18, 2013

Java :: Singleton Pattern

Definition
Singleton pattern is one of the most commonly used patterns, it is used to ensure that only one instance of an object is created, and as in the implementation example you can see that a check for a STATIC variable if not exists create one (and it will be only the first time off-course) then the same instance will be returned always.
Focus on that the main constructor for the class should be implemented as private to make sure that no one can create an object for your class using else than getInstance method

Implementation

 public class SingletonClass {
   private static SingletonClass instance;

   private SingletonClass() {}

   public static SingletonClass getInstance() {
    if(instance == null) {
     instance = new SingletonClass();
     return instance;
    } else {
      return instance;
   }
 }

No comments:

Post a Comment