diff --git a/notes/pics/dp-prototype.png b/notes/pics/dp-prototype.png index 9ec36b9a..82daeacd 100644 Binary files a/notes/pics/dp-prototype.png and b/notes/pics/dp-prototype.png differ diff --git a/notes/设计模式 - 原型模式.md b/notes/设计模式 - 原型模式.md index 543470ce..9606e8d2 100644 --- a/notes/设计模式 - 原型模式.md +++ b/notes/设计模式 - 原型模式.md @@ -3,6 +3,8 @@ ### 意图 使用原型实例指定要创建对象的类型,通过复制这个原型来创建新对象。 +客户端只持有 Prototype,调用 myClone() 就能得到一个同类型的新对象,不需要知道具体类;对象的初始化很耗时(例如要读取配置)时,复制已有对象的状态也比从头初始化更快。 + ### 类图

@@ -16,20 +18,20 @@ public abstract class Prototype { ```java public class ConcretePrototype extends Prototype { - private String filed; + private String field; - public ConcretePrototype(String filed) { - this.filed = filed; + public ConcretePrototype(String field) { + this.field = field; } @Override Prototype myClone() { - return new ConcretePrototype(filed); + return new ConcretePrototype(field); } @Override public String toString() { - return filed; + return field; } } ``` @@ -51,7 +53,9 @@ abc ### JDK 中的应用 - [java.lang.Object#clone()](http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#clone%28%29) +需要注意的是,Object#clone() 默认是浅拷贝:只复制字段的值,引用类型的字段在副本中仍指向同一个对象,需要深拷贝时要在 clone() 中再复制这些对象。类还要实现 Cloneable 接口,否则调用 super.clone() 会抛出 CloneNotSupportedException。 + ## 参考资料 - 弗里曼. Head First 设计模式 [M]. 中国电力出版社, 2007. -- Gamma E. 设计模式: 可复用面向对象软件的基础 [M]. 机械工业出版社, 2007. +- Gamma E. 设计模式:可复用面向对象软件的基础 [M]. 机械工业出版社, 2007.