作用
将克隆过程委派给被克隆的实际对象,当子类的属性特别多的时候,对其进行克隆甚至可以替换子类的构造。
优点
- 可以克隆对象,不需要所属的具体类进行耦合
- 可以克隆预生成原型,避免反复运行初始化代码
代码示例
Java
public abstract class Animal{
public String name;
public int age;
public Animal(){}
public Animal(Animal target ){
this.name = target.name;
this.age = target.age;
}
public abstract Animal clone();
pulic boolean equals(Object obj){
if (!(obj instanceof Animal)) return false;
obj = (Animal)obj;
if (obj.age == this.age && Objects.equals(this.name, obj.name)) return true;
return false;
}
}
public class Dog extend Animal{
public string call;
public Dog(){}
public Dog(Dog dog){
super(dog);
if (dog != null) {
this.call = dog.call
}
}
@Override
public Animal clone(){
return new Dog(this);
}
public boolean equals(Object obj){
if (!(obj instanceof Dog)|| !super.equals(obj)) return false;
obj = (Dog)obj;
if (Objects.equals(obj.call, this.call)) return true;
return false;
}
}
public class Demo{
public static void main(String[] args){
Dog dog = new Dog();
dog.call = "wang";
dog.name = "dog";
dog.age = 6;
Dog newDog = dog.clone();
}
}
Python
import copy
class Parent(object):
def __init__(self, element):
self.element = element
def __copy__(self):
element = copy.copy(self.element)
new = self.__class__(element)
new.__dict__.update(self.__dict__)
return new
def __deepcopy__(self, memodict={}):
element = copy.deepcopy(self.element)
new = self.__class__(element)
new.__dict__ = copy.deepcopy(self.__dict__)
return new