Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement the prototype pattern?

The objective of prototype pattern is to clone an object by reducing the cost of creation. Here is an example:

class Complex {
    int[] nums = {1,2,3,4,5};
    public Complex clone() {
        return new Complex();//this line create a new object, so is it violate the objective             of prototype ?//
    }
}

class Test2 {
   Complex c1 = new Complex();
   Complex makeCopy() {
      return (Complex)c1.clone();// Is it actually create a new object ? based on the clone method in Complex class? //
   }
   public static void main(String[] args) {
       Test2 tp = new Test2();
       Complex c2 = tp.makeCopy();
   }
}

I think it is for deep copy. So, can someone help me on this question ???

like image 978
user426546 Avatar asked Nov 15 '22 08:11

user426546


1 Answers

First of all, to get this working your Complex class needs to implement the Cloneable marker interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class. Then you need to override the Object.clone() method to specify the copy behaviour:

public Complex clone(){
    Complex clone = (Complex)super.clone();
    clone.nums = this.nums;
    return clone;
}
like image 152
Jeroen Rosenberg Avatar answered Dec 16 '22 20:12

Jeroen Rosenberg