设计模式学习笔记六:原型设计模式

在java中,原型实现Cloneable接口实现clone接口方法。

在使用过程应该注意的一点是,Object的clone方法是不复制对象的,只会复制对象的引用,也就是说仅仅复制了对象的内存地址。所以人们常说的浅拷贝和深拷贝说的就是是否要复制对象值的操作。


代码如下:

public class Run {

    public static void main(String[] args) {
        Prototype prototype = new Prototype();
        Prototype cp = prototype.clone();
        cp.run();
    }

}

class Prototype implements Cloneable {
    @Override
    protected Prototype clone(){
        Prototype prototype = null;
        try {
            prototype = (Prototype) super.clone();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return prototype;
    }
    public void run() {
        System.out.println("Run...");
    }
}
原文地址:https://www.cnblogs.com/liushijie/p/4712916.html