Prototype Pattern
If the cost of creating a new object is large and creation is resource intensive, we clone the object to avoid creation.
Clone is usually a shallow copy wherein the original and the cloned object referring to the same copy of the referenced lower-level object. But we can implement clone method to be a deep copy. In a deep copy, the original top-level object and all of its primitive members are duplicated, any lower-level objects that the top-level object contains are also duplicated so the original and the cloned object refer to two different lower-level objects
// shallow class X implements Cloneable { public Object clone() { try { //shallow copy return super.clone(); } catch (CloneNotSupportedException e) { return null; } } // deep class X implements Cloneable { B b; //reference to another object int i; //primitive members public Object clone() { X x= new X(i , b); //Deep copy of B return x; } public X (int i , B bb) { b = new B(bb);//this is a simple example. B can be created in any other way } }
page_revision: 2, last_edited: 1210850960|%e %b %Y, %H:%M %Z (%O ago)





