飞雪连天射白鹿,笑书神侠倚碧鸳

0%

【23种设计模式】5原型模式

描述:用原型实例指定创建对象的种类,拷贝原型创建新对象
优点:简化创建新对象的过程,动态获取对象运行时,属性修改父变子变
缺点:修改已有类时,违反开闭原则

应用:创建成本较大的场景,需要动态获取当前对象运行状态的场景


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());
听说,打赏我的人最后都找到了真爱
↘ 此处应有打赏 ↙
// 用户脚本