设计模式-原型模式

33 阅读1分钟

定义

原型模式,是一种创建型设计模式,允许对象通过复制现有对象的方式来创建新对象,而不是通过实例化类的方式。

这种模式特别有用在创建对象的成本比较大时,或者当需要一个对象与现有对象相似但又有部分差异的时。

UML 图

typescript 实现

1. 定义原型接口

interface Prototype {
  clone(): Prototype;
}

2. 创建具体原型类

class ConcretePrototype implements Prototype {
  private field1: Date;
  private field2: Object;

  constructor() {
    this.filed1 = new Date();
    this.filed2 = { name: 'ConcretePrototype', age: 22};
  }
  clone(): this {
    return structuredClone(this);
  }
}

3. 示例

const t = new ConcretePrototype();const t2 = t.clone();
console.log(t === t2);
console.log(JSON.stringify(t, null, 2));
console.log(JSON.stringify(t2, null, 2));

通用实现

// 公共部分
export abstract class Prototype {
  clone(): this {
    return structuredClone(this);
  }
}

// 私有部分
class Teacher extends Prototype {
  constructor() {
    super();
    this.name = "flywen";
    this.birthday = new Date();
  }
}

// 私有部分,示例
const t1 = new Teacher();
const t2 = t1.clone();
console.log(t1 === t2);
console.log(t1, JSON.stringify(t1, null, 2));
console.log(t2, JSON.stringify(t2, null, 2));