定义

用原型实例指定创建对象的种类,并且通过拷贝这些原型,创建新的对象

优缺点

优点
简化创建新对象的过程并提高效率;可动态获取对象的运行时的状态;原始对象变化(增加或减少属性)相应克隆对象也会变化
缺点
对已有的类修改时,需要修改源码,违背了OCP原则

应用场景

创建成本比较大的场景;需要动态获取当前的对象运行状态的场景

角色

  • Prototype:抽象原型对象
  • ConcretePrototype:具体原型角色

    类图

    image.png

    代码

    ```typescript interface Prototype { clone():Prototype; }

class Dog implements Prototype { public name: string; public birthYear: number; public sex: string; public presentYear: number; constructor() { this.name = “lili”; this.birthYear = 2015; this.sex = “男”; this.presentYear = 2018; }

  1. public getDiscription(): string {
  2. return `狗狗叫${this.name},性别${this.sex},${this.presentYear}年${this.presentYear - this.birthYear}岁了`
  3. }
  4. // 实现复制
  5. public clone(): Prototype {
  6. return Object.create(this);
  7. }

}

// 使用 const dog = new Dog(); console.log(dog.getDiscription()); dog.presentYear = 2020; const dog1 = Object.create(dog); console.log(dog1.getDiscription()); ```