Previous | Home | Next |
The prototype pattern is allow us to copy of an existing object or allow to clone of an existing object instead of creating the new object and It may be also customized as per the requirement. It is allow to copy the existing objects for avoid so much overhead. We can implement the clone method by the clonable interface for copy of the existing object.
- It supports for specifying the new objects with varying structure and varying values.
- It also allow to adding and removing products at runtime.
- It allow dynamically configuring the classes for an application and reducing sub-classes.
The prototype pattern is used when we are not interested into construction of a class hierarchy of factories that is parallel to products class hierarchy. The class Instances have only one combination of state, and the classes are instantiated at run-time.
Example
package r4r; class Complex { int[] nums = {2,4,5,1,3}; public Complex clone() { return new Complex(); } int[] getNums() { return nums; } } class prototypetests { Complex c1 = new Complex(); Complex makeCopy() { return (Complex)c1.clone(); } public static void main(String[] args) { prototypetests pp = new prototypetests(); Complex cx = pp.makeCopy(); int[] mycopy = cx.getNums(); mycopy[0] = 5; System.out.println(); System.out.print("local array: "); for(int i = 0; i < mycopy.length; i++) System.out.print(mycopy[i]); System.out.println(); System.out.print("clon of object: "); for(int j = 0; j < cx.nums.length; j++) System.out.print(cx.nums[j]); System.out.println(); System.out.print("Original object: "); for(int k = 0; k < pp.c1.nums.length; k++) System.out.print(pp.c1.nums[k]); } }
Previous | Home | Next |