定义
用原型实例指定创建对象的种类,并且通过拷贝这些原型,创建新的对象
优缺点
优点
简化创建新对象的过程并提高效率;可动态获取对象的运行时的状态;原始对象变化(增加或减少属性)相应克隆对象也会变化
缺点
对已有的类修改时,需要修改源码,违背了OCP原则
应用场景
角色
- Prototype:抽象原型对象
- ConcretePrototype:具体原型角色
类图
代码
```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; }
public getDiscription(): string {return `狗狗叫${this.name},性别${this.sex},${this.presentYear}年${this.presentYear - this.birthYear}岁了`}// 实现复制public clone(): Prototype {return Object.create(this);}
}
// 使用 const dog = new Dog(); console.log(dog.getDiscription()); dog.presentYear = 2020; const dog1 = Object.create(dog); console.log(dog1.getDiscription()); ```
