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.
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.
Runtime loading of a class.
ReplyDeleteClass loaded only once in JVM.