设计模式五:原型模式

创建型模式最后一种 原型模式 (一般用于框架)或者称为克隆模式

使用场景:当对象创建比较繁琐 耗时 或者有访问权限的时候 可以使用原型模式 (以某个对象为原型 复制出新的对象 不同于new)

实现:

 实现Cloneable 接口和重写clone方法(内存赋值)

public class Sheep implements Cloneable {
    public String name;

    public Date birth;

    public String getName() {
        return name;
    }

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

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    /**
     * 使用birth对象clone 是为了实现被克隆对象与原有对象完全分离 否则 像birth 会指向同一个地址
     * @return
     * @throws CloneNotSupportedException
     */
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Sheep obj = (Sheep) super.clone();
        obj.birth = (Date) this.birth.clone();
        return obj;
    }
}

猜你喜欢

转载自blog.csdn.net/youth_never_go_away/article/details/80757264