欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

设计模式:创建型 - 原型模式

程序员文章站 2022-06-13 15:52:29
...

 

 

JAVA:

浅复制:Work 类 中数据不会被克隆

class ProtoType implements Cloneable{
    private String id;
    private Work work;

    public String getId() {return id;}
    public void setId(String id) {this.id = id;}
    public Work getWork() {return work;}
    public void setWork(Work work) {this.work = work;}

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

class Work{
    private String name;

    public String getName() {return name;}
    public void setName(String name) {this.name = name;}
}

深复制:

class Work implements Cloneable{
    private String name;

    public String getName() {return name;}
    public void setName(String name) {this.name = name;}

    // Work 也实现 Cloneable 类
    @Override
    protected Object clone() throws CloneNotSupportedException {return super.clone();}
}
class ProtoType implements Cloneable{
    private String id;
    private Work work;

    public String getId() {return id;}
    public void setId(String id) {this.id = id;}
    public Work getWork() {return work;}
    public void setWork(Work work) {this.work = work;}

    @Override
    protected Object clone() throws CloneNotSupportedException {
        // work利用引用地址克隆
        ProtoType protoType = (ProtoType)super.clone();
        protoType.setWork((Work)protoType.getWork().clone());
        return protoType;
    }
}