Wednesday, August 15, 2012

Singleton Design Pattern

Singleton Design Pattern:

The singleton pattern is one of the simplest design patterns. it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance. in this case the same instance can be used from everywhere, being impossible to invoke directly the constructor each time.


Example:

package com.jsl.core;
import java.io.Serializable;
 
public class Singleton implements Serializable{
 
   private static final long serialVersionUID = 1L;
   private static Singleton obj;
 
   private Singleton() {
   }
 
   public static Singleton getObject() {
      if (obj == null) {
        synchronized (Singleton.class) {
          if (obj == null)
              obj = new Singleton();
        }
      }
      return obj;
   }
   @Override
   protected Object clone() throws CloneNotSupportedException {
    
     throw new CloneNotSupportedException("Object can't be created by using clone method");
                        
   }
}

No comments:

Post a Comment

Spring Boot 3 : JWT with SecurityFilterChain, AuthorizeHttpRequests, RequestMatchers

pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"...