6. 原型模式(Prototype)

Intent

使用原型实例指定要创建对象的类型,通过复制这个原型来创建新对象。

Class Diagram

设计模式 - 原型模式 - 图1

Implementation

  1. public abstract class Prototype {
  2. abstract Prototype myClone();
  3. }
  1. public class ConcretePrototype extends Prototype {
  2. private String filed;
  3. public ConcretePrototype(String filed) {
  4. this.filed = filed;
  5. }
  6. @Override
  7. Prototype myClone() {
  8. return new ConcretePrototype(filed);
  9. }
  10. @Override
  11. public String toString() {
  12. return filed;
  13. }
  14. }
  1. public class Client {
  2. public static void main(String[] args) {
  3. Prototype prototype = new ConcretePrototype("abc");
  4. Prototype clone = prototype.myClone();
  5. System.out.println(clone.toString());
  6. }
  7. }
  1. abc

JDK

设计模式 - 原型模式 - 图2