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

来源:互联网 发布:藏民对十一世班禅 知乎 编辑:程序博客网 时间:2024/05/01 04:03

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

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


代码如下:

package com.array7.prototype;public class Run {public static void main(String[] args) {Prototype prototype = new Prototype();Prototype cp = prototype.clone();cp.run();}}class Prototype implements Cloneable {@Overrideprotected Prototype clone(){Prototype prototype = null;try {prototype = (Prototype) super.clone();} catch (Exception e) {e.printStackTrace();}return prototype;}public void run() {System.out.println("Run...");}}


0 0
原创粉丝点击