原型模式
# 6. 原型模式(Prototype)
# Intent
使用原型实例指定要创建对象的类型,通过复制这个原型来创建新对象。
# Class Diagram
# Implementation
package com.code.factory.example3;
public abstract class Prototype {
abstract Prototype myClone();
}
1
2
3
4
5
2
3
4
5
package com.code.factory.example3;
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
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.code.factory.example3;
public class Main {
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
8
9
2
3
4
5
6
7
8
9
abc
1