mirror of
https://github.com/CyC2018/Interview-Notebook.git
synced 2026-10-31 19:13:42 +00:00
Update 设计模式 - 原型模式.md
重新绘制类图 dp-prototype.png;补充原型模式使用场景及 Object#clone() 浅拷贝说明,调整示例代码并完成文字校对。
This commit is contained in:
Binary file not shown.
|
Before Width: | Height: | Size: 147 KiB After Width: | Height: | Size: 147 KiB |
+10
-6
@@ -3,6 +3,8 @@
|
||||
### 意图
|
||||
使用原型实例指定要创建对象的类型,通过复制这个原型来创建新对象。
|
||||
|
||||
客户端只持有 Prototype,调用 myClone() 就能得到一个同类型的新对象,不需要知道具体类;对象的初始化很耗时(例如要读取配置)时,复制已有对象的状态也比从头初始化更快。
|
||||
|
||||
### 类图
|
||||
<div align="center"> <img src="pics/dp-prototype.png" width="760px"/> </div><br>
|
||||
|
||||
@@ -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.
|
||||
|
||||
Reference in New Issue
Block a user