homework: 单例模式

  1. class Demo {
  2. private static instance: Demo;
  3. private constructor(public name: string) {};
  4. static getInstance(name: string): Demo {
  5. if (!this.instance) {
  6. this.instance = new Demo(name);
  7. }
  8. return this.instance;
  9. }
  10. }
  11. const d1 = Demo.getInstance('Jack');
  12. const d2 = Demo.getInstance('Lily');
  13. console.log(d1.name);
  14. console.log(d2.name);
  15. // Jack
  16. // Jack

homework: 接口重载

Flyweight Pattern(享元模式):主要用于减少创建对象的数量,以减少内存占用和提高性能。

  1. type OrderID = string & { readonly brand: unique symbol };
  2. type UserID = string & { readonly brand: unique symbol };
  3. type ID = OrderID | UserID;
  4. // (伴侣模式): 一种非正式编程约束
  5. function OrderID (id: string) {
  6. return id as OrderID;
  7. }
  8. function UserID (id: string) {
  9. return id as UserID;
  10. }
  11. function queryForUser(id: ID) {}
  12. queryForUser('ll');
  13. // Argument of type 'string' is not assignable to parameter of type 'ID'.ts(2345)
  14. queryForUser(UserID('ll'));