原型设计模式

作用

将克隆过程委派给被克隆的实际对象,当子类的属性特别多的时候,对其进行克隆甚至可以替换子类的构造。

优点

  • 可以克隆对象,不需要所属的具体类进行耦合
  • 可以克隆预生成原型,避免反复运行初始化代码

代码示例

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值