Sabtu, 25 Februari 2017

Prototype Design Pattern

In the prototype pattern, a new object is created by cloning an existing object. The prototype pattern can be a useful way of creating copies of objects.

One example of how this can be useful is, if an original object is created with a resource such as a data stream that may not be available at the time that a clone of the object is needed.  Another example is if the original object creation involves a significant time commitment, such as reading data from a database or over a network.


Advantages of Prototype Design 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.

Let's see with the help of an example how to implement prototype desing pattern. To do so, we'll create a Prototype interface that features a cloning() method.

       
package com.rd;

public interface Prototype {

Prototype cloning();
}

       
package com.rd;

public class WeatherInfo implements Prototype {

private double temprature;
private String state;


public WeatherInfo(double temprature, String state) {
super();
this.temprature = temprature;
this.state = state;
}

public void showWeatherInfo(){
System.out.println(state+" temprature is "+temprature);
}


@Override
public Prototype cloning() {
return new WeatherInfo(temprature,state);
}

}

       
package com.rd;

public class PrototypeDemo {

public static void main(String[] args) {

WeatherInfo weatherInfo = new WeatherInfo(17, "Delhi");
weatherInfo.showWeatherInfo();

WeatherInfo cloneObject = (WeatherInfo)weatherInfo.cloning();
cloneObject.showWeatherInfo();
}

}


Tidak ada komentar:

Posting Komentar