读书人

原形模式的Java实现

发布时间: 2012-12-28 10:29:05 作者: rapoo

原型模式的Java实现

(Prototype)原型模式的Java实现

???? 总之,Java中原型模式clone()方法对我们隐藏了许多细节,或者说必要操作,它的实现机制涉及到了反射、IO流操作、序列化等,只有弄清楚这一系列的知识才能更深入地理解这些相关的知识点。<!--EndFragment--><!--EndFragment-->//原型01,实现Cloneable接口并覆盖clone()方法
class ConcretePrototype01 implements Cloneable {
??private String name;

??public ConcretePrototype01(String name) {
????this.name = name;
??}
????
??public void getName() {
????System.out.println(name);
??}
????
??//覆盖Object基类中的clone()方法,并扩大该方法的访问权限,具体化返回本类型
??public ConcretePrototype01 clone() {
????ConcretePrototype01 self = null;
????try {
??????self = (ConcretePrototype01) super.clone();
????} catch (CloneNotSupportedException e) {
??????e.printStackTrace();
????}
????return self;
??}
}

//测试类
public class Client {
??public static void main(String[] args) {
????ConcretePrototype01 prototype01 = new ConcretePrototype01("蚂蚁 ...");
????prototype01.getName();
????
????//通过clone获得一个拷贝
????ConcretePrototype01 fromClone01 = prototype01.clone();
????fromClone01.getName();
??}
}

本文出自 “蚂蚁” 博客,请务必保留此出处http://haolloyin.blog.51cto.com/1177454/333442

读书人网 >编程

热点推荐