设计模式原则
1. 创建型
工厂模式
A.简单工厂模式
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 35 36 37 38 39 40 41 42 43
| interface IPhone { name: string; price: number; }
enum Phones { hw, mi, }
class Shop { hwPhone: IPhone = { name: "mate 40", price: 4000, };
miPhone: IPhone = { name: "p40", price: 4000, };
getPhone(type: Phones): IPhone { switch (type) { case Phones.hw: return this.hwPhone; case Phones.mi: return this.miPhone; } } }
const shop1 = new Shop(); const mi1 = shop1.getPhone(Phones.mi); mi1.name = "nihao";
const shop2 = new Shop(); const mi2 = shop2.getPhone(Phones.mi);
console.log(mi1, mi2);
|
B.工厂方法模式
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
| interface IPhone { name: string; price: number; } class Phone { name: string; price: number;
constructor(name: string, price: number) { this.name = name; this.price = price; } }
class Shop { getPhone(name: string, price: number): IPhone { return new Phone(name, price); } }
const shop1 = new Shop(); const phone1 = shop1.getPhone("华为", 4500);
const shop2 = new Shop(); const phone2 = shop2.getPhone("小米", 4000);
console.log(phone1, phone2);
|
C.抽象工厂模式
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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
|
abstract class Phone { name: string; price: number;
constructor(name: string, price: number) { this.name = name; this.price = price; }
abstract call(): void; }
abstract class Laptop { name: string; price: number;
constructor(name: string, price: number) { this.name = name; this.price = price; }
abstract game(gameName: string): void; }
class MiPhone extends Phone { call() { console.log("少林功夫好哎"); } }
class MiLaptop extends Laptop { game(gameName: string) { console.log(`小米电脑适合${gameName}`); } }
class Mi { getPhone(name: string, price: number) { return new MiPhone(name, price); }
getLaptop(name: string, price: number) { return new MiLaptop(name, price); } }
class HuaweiPhone extends Phone { call() { console.log("少林功夫好哎"); } }
class HuaweiLaptop extends Laptop { game(gameName: string) { console.log(`小米电脑适合${gameName}`); } }
class Huawei { getPhone(name: string, price: number) { return new HuaweiPhone(name, price); }
getLaptop(name: string, price: number) { return new HuaweiLaptop(name, price); } }
const miShop = new Mi(); const miPhone = miShop.getLaptop("P40", 3600); console.log(miPhone);
const huaweiShop = new Huawei(); const huaweiPhone = huaweiShop.getLaptop("meta 40", 4000); console.log(huaweiPhone);
|
个人理解的工厂模式,本身就是一种组装拼接,各种具有共同属性抽成一个共性类,有时带着特殊的方法以便继承;通过 new 和继承的方式实现组装;
单例模式
1 2 3 4
| function f() {} const a = f.prototype, b = Object.getPrototypeOf(f); console.log(a, b);
|
订阅发布者模式