Skip to content

Commit 39db90c

Browse files
committed
修改 README
1 parent 695aaf6 commit 39db90c

File tree

1 file changed

+38
-3
lines changed

1 file changed

+38
-3
lines changed

prototype/README.md

Lines changed: 38 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,49 @@
1-
# 模式
1+
# 原型模式 ( Prototype )
22

33
## 用途
44

5-
>
5+
> 用原型实例指定创建对象的种类, 并且通过拷贝这些原型创建新的对象
66
77
## 实例
88

9-
>
9+
> 首先要联想到克隆,最经典的一个例子就是克隆羊多利了。原型模式的核心就是在已经提供的对象的基础上来构造一个新的对象
1010
1111
## 模式分析
1212

13+
> 在 Java 中,克隆操作可以通过实现 Cloneable 接口并且重写定义于 Object 类中的 clone() 方法
14+
```
15+
public Sheep implements Cloneable {
16+
private String name;
17+
public Sheep(String name){
18+
this.name = name;
19+
}
20+
public void setName(String name){
21+
this.name = name;
22+
}
23+
public String getName(){
24+
return this.name;
25+
}
26+
@Override
27+
public Sheep clone() throws CloneNotSupportedException {
28+
return new Sheep(this.name);
29+
}
30+
}
31+
```
32+
> 克隆一个羊对象可以这样操作
33+
```
34+
...
35+
Sheep origin = new Sheep("团团");
36+
System.out.println(origin.getName()); //团团
37+
38+
origin.setName("圆圆");
39+
Sheep clone = origin.clone();
40+
System.out.println(clone.getName()); //圆圆
41+
...
42+
```
1343

1444
## 适用场景
45+
46+
> 当一个系统应该独立于它的产品创建、 构成和表示时, 要使用Prototype模式; 以及
47+
>* 当要实例化的类是在运行时刻指定时, 例如, 通过动态装载
48+
>* 为了避免创建一个与产品类层次平行的工厂类层次时
49+
>* 当一个类的实例只能有几个不同状态组合中的一种时,建立相应数目的原型并克隆它们可能比每次用合适的状态手工实例化该类更方便一些

0 commit comments

Comments
 (0)