Prototype Pattern


This creational pattern addresses another design problem. There are times when instantiating an object is a very costly operation. It is not possible to go through the entire process again and again. At the same time, we do need many instances of the class. The Prototype pattern is used to address such constraints.

Prototype is based on cloning. The Factory class contains individual instances of the different configurations of the product class. Based on the parameters passed to the factory method, it clones the particular object and passes on an instance.

Now here is the catch. How deep should we clone it? We chose cloning because we wanted it to be easier and faster. But if the cloning itself gets complicated, then we are defeating the purpose. On the other hand, if we make a very shallow clone, then we defeat the purpose of cloning itself!

That depends upon the required functionality. Prototype is very useful when the actual object is trivially simple, but it requires extreme processing to instantiate. We can avoid that processing by using a prototype pattern.

Consider for example, if we are working on implementing an image processing algorithm. If we want to an object that contains the convolution matrix built out of these images. We want to use this matrix to perform a lot more processing. It is a meaningless effort to rework the convolutions again and again. Also, it is not possible to do all the processing on one instance of this matrix - because the processing will destroy the current data. The Prototype pattern can help us solve such a problem.

The Prototype holder can evaluate the matrices for once and hold them within it. On every call to the factory method, it can return a cloned copy of this matrix. The caller can then mess with this copy without disrupting what is contained in the container. Next time we need the matrix, we can just invoke the factory method once again.

Implementation


Let us now look at how the Prototype pattern in implemented in code:

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();
	}
}