Pages

Showing posts with label Cloning. Show all posts
Showing posts with label Cloning. Show all posts

Sunday, 27 September 2015

Prototype Design Pattern

This pattern is used when creation of object directly is costly. Prototype Pattern says that cloning of an existing object instead of creating new one and can also be customized as per the requirement.

For example,
Suppose we are doing a sales analysis on a set of data from a database. Normally, we would copy the information from the database, encapsulate it into an object and do the analysis. But if another analysis is needed on the same set of data, reading the database again and creating a new object is not the best idea. If we are using the Prototype pattern then the object used in the first analysis will be cloned and used for the other analysis.





public interface Prototype {
      public abstract Object clone ( );
}

public class ConcretePrototype implements Prototype {
      public Object clone() {
            return super.clone();
      }
}

public class Client {
      public static void main( String arg[] ) {
            ConcretePrototype obj1= new ConcretePrototype ();
            ConcretePrototype obj2 = (ConcretePrototype)obj1.clone();
      }
}

Application:
Session replication from one server to another server.
Generating the GUI having many numbers of similar controls.

Advantage of Prototype Pattern
It reduces the need of sub-classing.
It hides complexities of creating objects.
The clients can get new objects without knowing which type of object it will be.
It lets you add or remove objects at runtime.

Usage of Prototype Pattern
When the classes are instantiated at runtime.
When the cost of creating an object is expensive or complicated.
When you want to keep the number of classes in an application minimum.
When the client application needs to be unaware of object creation and representation.

Sunday, 19 July 2015

Singleton Design Pattern - A Creational Design Patterns

Ensures at most one instance of a particular class is ever created in your application.

Project Configuration: Class that reads your project configuration should be made Singleton by reads once and holds on application Cache and global access to all classes in application.

Application Log: Logger must be initialized once and used everywhere in application.

Analytics and Reporting: If you are using some kind of data analysis tool like Google Analytics, you will notice that they are designed to be singleton. It initializes once and being used everywhere for each user action.

Singleton and Thread Safety

Two instances of Singleton class will be created if the getInstance() called simultaneously by two threads. By making getInstance() method synchronized we will ensure that no two threads can be entered into getInstance() method at the same time.

public static synchronized Singleton getInstance() {
       /* Lazy initialization, creating object on first use */
       if (instance == null) {
              synchronized (Singleton.class) {
                     if (instance == null) {
                           instance = new Singleton();
                     }
              }
       }
       return instance;
}

Singleton and Early Initialization
Using early initialization we will initialize upfront before your class is being loaded. This way you don’t need to check for synchronization as it is initialized before being used ever.

Singleton and Object Cloning
Cloning is used to create a copy of object at any instance original object by implementing java.lang.Cloneable interface and override clone() method from Object class.

To prevent cloning on singleton object, explicitly throw CloneNotSupportedException exception in clone() method.

Singleton and Serialization

Java Serialization allows converting the state of an object into stream of bytes to store or transfer. Deserialization used to convert byte stream into. If a singleton class desterilized, it will end up creating duplicate objects.

To resolve this issue, we need to include readResolve() method in our class which will be invoked before the object is deserialized. We will return INTANCE by call getInstance() method inside readResolve() which will ensure single instance of Singleton class is exist application.


import java.io.Serializable;
class Singleton implements Cloneable, Serializable {
       private static final long serialVersionUID = 1L;
       private static volatile Singleton instance;
       private int value;

       /* Private Constructor prevents any other class from instantiating */
       private Singleton() {
       }
       public static synchronized Singleton getInstance() {

              /* Lazy initialization, creating object on first use */
              if (instance == null) {
                     synchronized (Singleton.class) {
                           if (instance == null) {
                                  instance = new Singleton();
                           }
                     }
              }
              return instance;
       }

       /* Restrict another object creation in serialization. */
       protected Object readResolve() {
              return getInstance();
       }

       /* Restrict cloning of object */
       @Override
       public Object clone() throws CloneNotSupportedException {
              throw new CloneNotSupportedException();
       }

       public void display() {
              System.out.println("Hurray! I am display from Singleton!");
       }

       public int getValue() {
              return value;
       }

       public void setValue(int value) {
              this.value = value;
       }
}

Singleton Design Pattern

Singleton design pattern – Creational Design Patterns

Ensures at most one instance of a particular class is ever created in your application.

Project Configuration: Class that reads your project configuration should be made Singleton by reads once and holds on application Cache and global access to all classes in application.

Application Log: Logger must be initialized once and used everywhere in application.

Analytics and Reporting: If you are using some kind of data analysis tool like Google Analytics, you will notice that they are designed to be singleton. It initializes once and being used everywhere for each user action.

Singleton and Thread Safety

Two instances of Singleton class will be created if the getInstance() called simultaneously by two threads. By making getInstance() method synchronized we will ensure that no two threads can be entered into getInstance() method at the same time.

public static synchronized Singleton getInstance() {
       /* Lazy initialization, creating object on first use */
       if (instance == null) {
              synchronized (Singleton.class) {
                     if (instance == null) {
                           instance = new Singleton();
                     }
              }
       }
       return instance;
}

Singleton and Early Initialization
Using early initialization we will initialize upfront before your class is being loaded. This way you don’t need to check for synchronization as it is initialized before being used ever.

Singleton and Object Cloning
Cloning is used to create a copy of object at any instance original object by implementing java.lang.Cloneable interface and override clone() method from Object class.

To prevent cloning on singleton object, explicitly throw CloneNotSupportedException exception in clone() method.

Singleton and Serialization

Java Serialization allows converting the state of an object into stream of bytes to store or transfer. Deserialization used to convert byte stream into. If a singleton class desterilized, it will end up creating duplicate objects.

To resolve this issue, we need to include readResolve() method in our class which will be invoked before the object is deserialized. We will return INTANCE by call getInstance() method inside readResolve() which will ensure single instance of Singleton class is exist application.


import java.io.Serializable;
class Singleton implements Cloneable, Serializable {
       private static final long serialVersionUID = 1L;
       private static volatile Singleton instance;
       private int value;

       /* Private Constructor prevents any other class from instantiating */
       private Singleton() {
       }
       public static synchronized Singleton getInstance() {

              /* Lazy initialization, creating object on first use */
              if (instance == null) {
                     synchronized (Singleton.class) {
                           if (instance == null) {
                                  instance = new Singleton();
                           }
                     }
              }
              return instance;
       }

       /* Restrict another object creation in serialization. */
       protected Object readResolve() {
              return getInstance();
       }

       /* Restrict cloning of object */
       @Override
       public Object clone() throws CloneNotSupportedException {
              throw new CloneNotSupportedException();
       }

       public void display() {
              System.out.println("Hurray! I am display from Singleton!");
       }

       public int getValue() {
              return value;
       }

       public void setValue(int value) {
              this.value = value;
       }
}