描述:用原型实例指定创建对象的种类,拷贝原型创建新对象
优点:简化创建新对象的过程,动态获取对象运行时,属性修改父变子变
缺点:修改已有类时,违反开闭原则
应用:创建成本较大的场景,需要动态获取当前对象运行状态的场景
classDiagram
class Prototype{
<>
clone():Prototype
}
class Dog{
+name: string
+birthYear: number
+sex: string
+presentYear: number
constructor()
+getDiscription() string
+clone() Prototype
}
Prototype <|-- Dog :实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| 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());
const dog1 = Object.create(dog); dog1.presentYear = 2020; console.log(dog1.getDiscription()); const dog2 = dog.clone(); console.log('--'); console.log(dog.getDiscription()); console.log(dog1.getDiscription()); console.log(dog2.getDiscription());
|