Search code examples
javadesign-patternsprototype-pattern

how does prototype pattern create a deep copy throw clone() method


I know that clone() method create a shallow copy and prototype pattern create a deep copy but i don't know how prototype work to do it by still using clone() method. What is the core element to create a new object clone.

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

}

Solution

  • Well I donot think that prototype pattern is a deep copy always(depends on how you implement/override the clone() method).

    1. It infact is a shallow copy if the class which overrides the clone method just calls the super.clone() as in your example above.

    2. If the overridden method of clone() iterates through the fields of the actual object which we are cloning and try to create a new copy of those objects and store it in the object which we get out by calling super.clone() only then can it be called as a deep copy.

    Until unless any class which implements the custom Prototype interface created and simple calls the super.clone() it would in turn be doing a shallow copy where in the parent and the cloned objects HAS A references of any external objects will both be pointing to same object and hence a shallow copy.

    Also note that in the example that you provided you need to make your interface Prototype to implement Cloneable marker interface.