创建型 - 原型模式(Prototype Pattern)
Salted Fish 2022/1/26 创建型
原型模式(Prototype),使用原型实例指定要创建对象的类型,通过复制这个原型来创建新对象。
# 意图
使用原型实例指定要创建对象的类型,通过复制这个原型来创建新对象。
# 类图
# 实现
public abstract class Prototype {
abstract Prototype myClone();
}
1
2
3
2
3
public class ConcretePrototype extends Prototype {
private String filed;
public ConcretePrototype(String filed) {
this.filed = filed;
}
@Override
Prototype myClone() {
return new ConcretePrototype(filed);
}
@Override
public String toString() {
return filed;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Client {
public static void main(String[] args) {
Prototype prototype = new ConcretePrototype("abc");
Prototype clone = prototype.myClone();
System.out.println(clone.toString());
}
}
1
2
3
4
5
6
7
2
3
4
5
6
7
abc
1
# JDK
# 参考
- 原型模式(Prototype) https://www.jianshu.com/p/1638e7b068c1
- 原型模式(Prototype)- 最易懂的设计模式解析 https://www.jianshu.com/p/7deb64f902db