2019-11-02 22:11:39 +08:00
|
|
|
|
## 6. 原型模式(Prototype)
|
|
|
|
|
|
|
|
|
|
### Intent
|
|
|
|
|
|
|
|
|
|
使用原型实例指定要创建对象的类型,通过复制这个原型来创建新对象。
|
|
|
|
|
|
|
|
|
|
### Class Diagram
|
|
|
|
|
|
2019-12-06 10:11:23 +08:00
|
|
|
|
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/b8922f8c-95e6-4187-be85-572a509afb71.png"/> </div><br>
|
2019-11-02 22:11:39 +08:00
|
|
|
|
|
|
|
|
|
### Implementation
|
|
|
|
|
|
|
|
|
|
```java
|
|
|
|
|
public abstract class Prototype {
|
|
|
|
|
abstract Prototype myClone();
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
```java
|
|
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
```java
|
|
|
|
|
public class Client {
|
|
|
|
|
public static void main(String[] args) {
|
|
|
|
|
Prototype prototype = new ConcretePrototype("abc");
|
|
|
|
|
Prototype clone = prototype.myClone();
|
|
|
|
|
System.out.println(clone.toString());
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
```html
|
|
|
|
|
abc
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
### JDK
|
|
|
|
|
|
|
|
|
|
- [java.lang.Object#clone()](http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#clone%28%29)
|