typescript設計模式 —— 生產型模式和結構型模式

重學設計模式

Design pattern implementations in TypeScript筆記。

五種創造性設計模式

單例模式

namespace SingletonPattern {
    export class Singleton {
        // A variable which stores the singleton object. Initially,
        // the variable acts like a placeholder
        private static singleton: Singleton;

        // private constructor so that no instance is created
        private constructor() {
        }

        // This is how we create a singleton object
        public static getInstance(): Singleton {
            // check if an instance of the class is already created
            if (!Singleton.singleton) {
                // If not created create an instance of the class
                // store the instance in the variable
                Singleton.singleton = new Singleton();
            }
            // return the singleton object
            return Singleton.singleton;
        }
    }
}

核心:維護一個實例,暴露統一的接口去獲取它,如果沒有則創建,如果有則直接返回。

抽象工廠模式

namespace AbstractFactoryPattern {
    export interface AbstractProductA {
        methodA(): string;
    }
    export interface AbstractProductB {
        methodB(): number;
    }

    export interface AbstractFactory {
        createProductA(param?: any) : AbstractProductA;
        createProductB() : AbstractProductB;
    }


    export class ProductA1 implements AbstractProductA {
        methodA = () => {
            return "This is methodA of ProductA1";
        }
    }
    export class ProductB1 implements AbstractProductB {
        methodB = () => {
            return 1;
        }
    }

    export class ProductA2 implements AbstractProductA {
        methodA = () => {
            return "This is methodA of ProductA2";
        }
    }
    export class ProductB2 implements AbstractProductB {
        methodB = () => {
            return 2;
        }
    }


    export class ConcreteFactory1 implements AbstractFactory {
        createProductA(param?: any) : AbstractProductA {
            return new ProductA1();
        }

        createProductB(param?: any) : AbstractProductB {
            return new ProductB1();
        }
    }
    export class ConcreteFactory2 implements AbstractFactory {
        createProductA(param?: any) : AbstractProductA {
            return new ProductA2();
        }

        createProductB(param?: any) : AbstractProductB {
            return new ProductB2();
        }
    }


    export class Tester {
        private abstractProductA: AbstractProductA;
        private abstractProductB: AbstractProductB;

        constructor(factory: AbstractFactory) {
            this.abstractProductA = factory.createProductA();
            this.abstractProductB = factory.createProductB();
        }

        public test(): void {
            console.log(this.abstractProductA.methodA());
            console.log(this.abstractProductB.methodB());
        }
    }

 }

核心:現在有四個商品,分別是A1、B1、A2、B2。A和B屬于兩種不同的商品緯度,而1、2則屬于商品等級。則核心就是A和B都是抽象產品角色,而創造出的A1、B1、A2、B2則是具體產品角色,而獲得具體產品的方法ConcreteFactory1ConcreteFactory2,就是具體工廠角色,而他們都實現了AbstractFactory這個抽象工廠。而最終的使用者Tester不用關心他到底是等級1還是等級2,直接使用傳入的具體工廠調用方法即可。

工廠方法模式

namespace FactoryMethodPattern {

    export interface AbstractProduct {
        method(param?: any) : void;
    }

    export class ConcreteProductA implements AbstractProduct {
        method = (param?: any) => {
            return "Method of ConcreteProductA";
        }
    }

    export class ConcreteProductB implements AbstractProduct {
        method = (param?: any) => {
            return "Method of ConcreteProductB";
        }
    }


    export namespace ProductFactory {
        export function createProduct(type: string) : AbstractProduct {
            if (type === "A") {
                return new ConcreteProductA();
            } else if (type === "B") {
                return new ConcreteProductB();
            }

            return null;
        }
    }
}

核心:
抽象產品: AbstractProduct、具體產品: ConcreteProductA、ConcreteProductB,產品工廠:ProductFactory。 通過傳入想要生產的產品類型,得到想要的產品。客戶端使用簡單,但是缺點是隨時產品的不斷增多,會不停的增加if else邏輯,不過在ts里完全可以通過map來屏蔽這個問題。

建筑者模式

namespace BuilderPattern {
    export class UserBuilder {
        private name: string;
        private age: number;
        private phone: string;
        private address: string;

        constructor(name: string) {
            this.name = name;
        }

        get Name() {
            return this.name;
        }
        setAge(value: number): UserBuilder {
            this.age = value;
            return this;
        }
        get Age() {
            return this.age;
        }
        setPhone(value: string): UserBuilder {
            this.phone = value;
            return this;
        }
        get Phone() {
            return this.phone;
        }
        setAddress(value: string): UserBuilder {
            this.address = value;
            return this;
        }
        get Address() {
            return this.address;
        }

        build(): User {
            return new User(this);
        }
    }

    export class User {
        private name: string;
        private age: number;
        private phone: string;
        private address: string;

        constructor(builder: UserBuilder) {
            this.name = builder.Name;
            this.age = builder.Age;
            this.phone = builder.Phone;
            this.address = builder.Address
        }

        get Name() {
            return this.name;
        }
        get Age() {
            return this.age;
        }
        get Phone() {
            return this.phone;
        }
        get Address() {
            return this.address;
        }
    }

}

核心:主要解決管道式構建的問題,Builder每次只能接收一個值,之后可能才能獲取到另一個值,最終才能創造出產品。
舉例:

(async () => {
 const ub = new UserBuilder('Jack');
const user = ub.setAge(await getAge(ub.getName)).setPhone('xxx').setAddress('xxx').build();
})()

原型模式

這一個設計模式有點不太懂源碼想表達的是什么。
但通常原型模式是為了解決new一個對象所損耗的資源太大,比如:

class A {
    private a1: string = '';
    private a2: string = '';
}

class User {
  private user = {};
  constructor(a: A, b, c, d, e, f, g, h, i) {
    /**
     * xxx....
     */
  }
}

這個時候new必須傳n個參數,并且參數可能會進行復雜運算,這個時候User就該繼承一個接口Cloneable,當我們想要創建的時候不必去new一個對象,而是直接clone:

class A {
    private a1: string = '';
    private a2: string = '';
}

export interface Cloneable<T> {
    clone(): T;
}

class User implements Cloneable<User> {
    private info: {
        a: A, b, c, d, e, f, g, h, I
    };

    constructor(a: A, b, c, d, e, f, g, h, i) {
      /**
       * xxx....
       */
      this.info = {
        a, b, c, d, e, f, g, h, I
      }
    }

    clone(): User {
        const { a, b, c, d, e, f, g, h, i } = this.info;
        const newUser = new User(a, b, c, d, e, f, g, h, i);
        return newUser;
    }
  }

需要注意的點是這里實現的是淺拷貝,由于a的類型是A,他也是一個對象,所以這樣clone出來的newUser,如果你修改了A的值newUser.a.a1 = 2,oldUser的A的值也會發生變化為2。所以想要深拷貝還得繼續改造這個clone方法。

原型模式的優點:

  • 簡化對象的創建過程,通過復制一個已有對象實例可以提高新實例的創建效率
  • 擴展性好
  • 提供了簡化的創建結構,原型模式中的產品的復制是通過封裝在原型類中的克隆方法實現的,無需專門的工廠類來創建產品

原型模式的缺點:

  • 需要為每一個類準備一個克隆方法,而且該克隆方法位于一個類的內部,當對已有類進行改造時,需要修改原代碼,違背了開閉原則。

七種結構型模式

適配器模式

namespace AdapterPattern {

    export class Adaptee {
        public method(): void {
            console.log("`method` of Adaptee is being called");
        }
    }

    export interface Target {
        call(): void;
    }

    export class Adapter implements Target {
        public call(): void {
            console.log("Adapter's `call` method is being called");
            var adaptee: Adaptee = new Adaptee();
            adaptee.method();
        }
    }
}

核心:將一個類的接口變換成客戶端所期待的另一種接口,從而使原本因接口不匹配而無法在一起工作的兩個類能夠一起工作。

  • 源對象: Adaptee
  • 目標對象:Target
  • 適配對象:Adapter
    具體使用場景:
class ConcreteTagert implements AdapterPattern.Target {
    call() {
        const adapter = new AdapterPattern.Adapter();
        adapter.call();
    }
}

const target = new ConcreteTagert();
target.call();

或者直接用adapter替換target。

橋接模式

namespace BridgePattern {

    export class Abstraction {
        implementor: Implementor;
        constructor(imp: Implementor) {
            this.implementor = imp;
        }

        public callIt(s: String): void {
            throw new Error("This method is abstract!");
        }
    }

    export class RefinedAbstractionA extends Abstraction {
        constructor(imp: Implementor) {
            super(imp);
        }

        public callIt(s: String): void {
            console.log("This is RefinedAbstractionA");
            this.implementor.callee(s);
        }
    }

    export class RefinedAbstractionB extends Abstraction {
        constructor(imp: Implementor) {
            super(imp);
        }

        public callIt(s: String): void {
            console.log("This is RefinedAbstractionB");
            this.implementor.callee(s);
        }
    }

    export interface Implementor {
        callee(s: any): void;
    }

    export class ConcreteImplementorA implements Implementor {
        public callee(s: any) : void {
            console.log("`callee` of ConcreteImplementorA is being called.");
            console.log(s);
        }
    }

    export class ConcreteImplementorB implements Implementor {
        public callee(s: any) : void {
            console.log("`callee` of ConcreteImplementorB is being called.");
            console.log(s);
        }
    }
}

主要解決問題:將抽象部分與它的實現部分分離,使它們都可以獨立地變化。

核心:

  • 抽象類Abstraction: 可以進行橋接的產品抽象,這里以apple watch類比。
  • 修成抽象類RefinedAbstractionA:抽象類的子類,定義了具體產品,例如apple watch的的商務版、運動版、定制版等。
  • 實現化角色Implementor:可以被橋接的產品抽象,定義了橋接的接口。類比apple watch的表帶,那么具體的接口,就可以看作是表帶的連接口。
  • 具體實現化角色ConcreteImplementorA:可以被橋接的具體產品。比如紅色塑料表帶,金屬表帶等。

這樣任意類型的apple watch就可以和任意類型的表帶進行組合,成為新的形態或者完成新的功能。

組合模式

namespace CompositePattern {
    export interface Component {
        operation(): void;
    }

    export class Composite implements Component {

        private list: Component[];
        private s: String;

        constructor(s: String) {
            this.list = [];
            this.s = s;
        }

        public operation(): void {
            console.log("`operation of `", this.s)
            for (var i = 0; i < this.list.length; i += 1) {
                this.list[i].operation();
            }
        }

        public add(c: Component): void {
            this.list.push(c);
        }

        public remove(i: number): void {
            if (this.list.length <= i) {
                throw new Error("index out of bound!");
            }
            this.list.splice(i, 1);
        }
    }

    export class Leaf implements Component {
        private s: String;
        constructor(s: String) {
            this.s = s;
        }
        public operation(): void {
            console.log("`operation` of Leaf", this.s, " is called.");
        }
    }
}

主要表示:部分-整體的層次結構。
核心:

  • Component:是組合中的對象聲明接口,在適當的情況下,實現所有類共有接口的默認行為。聲明一個接口用于訪問和管理Component子部件。
  • Leaf: 在組合中表示葉子結點對象,葉子結點沒有子結點。
  • Composite:定義有枝節點行為,用來存儲子部件,在Component接口中實現與子部件有關操作,如增加(add)和刪除(remove)等。

裝飾者模式


裝飾者模式隱含的是通過一條條裝飾鏈去實現具體對象,每一條裝飾鏈都始于一個Componet對象,每個裝飾者對象后面緊跟著另一個裝飾者對象,而對象鏈終于ConcreteComponet對象。

namespace DecoratorPattern {

    export interface Component {
        operation(): void;
    }

    export class ConcreteComponent implements Component {
        private s: String;

        constructor(s: String) {
            this.s = s;
        }

        public operation(): void {
            console.log("`operation` of ConcreteComponent", this.s, " is being called!");
        }
    }

    export class Decorator implements Component {
        private component: Component;
        private id: Number;

        constructor(id: Number, component: Component) {
            this.id = id;
            this.component = component;
        }

        public get Id(): Number {
            return this.id;
        }

        public operation(): void {
            console.log("`operation` of Decorator", this.id, " is being called!");
            this.component.operation();
        }
    }

    export class ConcreteDecorator extends Decorator {
        constructor(id: Number, component: Component) {
            super(id, component);
        }

        public operation(): void {
            super.operation();
            console.log("`operation` of ConcreteDecorator", this.Id, " is being called!");
        }
    }
}

核心:

  • 抽象組件:給出一個抽象接口,以規范所有實現對象。
  • 具體組建:實現了抽象畫組件接口。
  • 抽象裝飾:持有一個組件,并實現抽象組件的接口。
  • 具體裝飾:負責給組件對象添加上附加的功能。

應用:


裝飾

外觀模式

namespace FacadePattern {

    export class Part1 {
        public method1(): void {
            console.log("`method1` of Part1");
        }
    }

    export class Part2 {
        public method2(): void {
            console.log("`method2` of Part2");
        }
    }

    export class Part3 {
        public method3(): void {
            console.log("`method3` of Part3");
        }
    }

    export class Facade {
        private part1: Part1 = new Part1();
        private part2: Part2 = new Part2();
        private part3: Part3 = new Part3();

        public operation1(): void {
            console.log("`operation1` is called ===");
            this.part1.method1();
            this.part2.method2();
            console.log("==========================");
        }

        public operation2(): void {
            console.log("`operation2` is called ===");
            this.part1.method1();
            this.part3.method3();
            console.log("==========================");
        }
    }
}

核心:主要是解決為一組復雜的接口提供一個簡單的門面。
比如用戶下單操作,實際上我們首先需要調用用戶系統的驗證接口,其次要調用商品系統進行獲價,最后再調用訂單系統進行下單,同時還需要調用日志系統進行日志記錄。 進行外觀模式的架構后,我們只需要提供一個下單接口即可,剩下的細節用戶并不需要關心。

享元模式

namespace FlyweightPattern {

    export interface Flyweight {
        operation(s: String): void;
    }

    export class ConcreteFlyweight implements Flyweight {
        private instrinsicState: String;

        constructor(instrinsicState: String) {
            this.instrinsicState = instrinsicState;
        }

        public operation(s: String): void {
            console.log("`operation` of ConcreteFlyweight", s, " is being called!");
        }
    }

    export class UnsharedConcreteFlyweight implements Flyweight {
        private allState: number;

        constructor(allState: number) {
            this.allState = allState;
        }

        public operation(s: String): void {
            console.log("`operation` of UnsharedConcreteFlyweight", s, " is being called!");
        }
    }

    export class FlyweightFactory {

        private fliesMap: { [s: string]: Flyweight; } = <any>{};

        constructor() { }

        public getFlyweight(key: string): Flyweight {

            if (this.fliesMap[key] === undefined || null) {
                this.fliesMap[key] = new ConcreteFlyweight(key);
            }
            return this.fliesMap[key];
        }
    }
}

運用共享技術有效地支持大量細粒度的對象。

適用性:

  • 一個應用程序使用了大量的對象。
  • 完全由于使用大量的對象,造成很大的存儲開銷。
  • 對象的大多數狀態都可變為外部狀態。
  • 如果刪除對象的外部狀態,那么可以用相對較少的共享對象取代很多組對象。
  • 應用程序不依賴于對象標識。由于Flyweight對象可以被共享,對于概念上明顯有別的對象,標識測試將返回真值。

滿足以上的這些條件的系統可以使用享元對象。


享元

核心:一個具體的場景需要很多單元(享元),并且有非常多個場景,沒個單元都有自己的固有屬性,那么在組成這非常多個場景的時候,就能復用這些已經創建好的有估計屬性的單元。

比如:關系好的朋友一起合租,在廚房公用的場景下,廚房用具就是一個個單元。合租的每一組人就是一個場景,而鍋碗瓢盆不需要每一組人都買一個,如果沒有,那么買一個大家有人買了其他一起共用即可。

代理模式

namespace ProxyPattern {
    export interface Subject {
        doAction(): void;
    }

    export class Proxy implements Subject {
        private realSubject: RealSubject;
        private s: string;

        constructor(s: string) {
            this.s = s;
        }

        public doAction(): void {
            console.log("`doAction` of Proxy(", this.s, ")");
            if (this.realSubject === null || this.realSubject === undefined) {
                console.log("creating a new RealSubject.");
                this.realSubject = new RealSubject(this.s);
            }
            this.realSubject.doAction();
        }
    }

    export class RealSubject implements Subject {
        private s: string;

        constructor(s: string) {
            this.s = s;
        }
        public doAction(): void {
            console.log("`doAction` of RealSubject", this.s, "is being called!");
        }
    }
}

為其他對象提供一種代理以控制對這個對象的訪問。
代理對象可以在客戶端和目標對象之間起到中介的作用,這樣起到了中介的作用和保護了目標對象的作用。
客戶端不需要知道真正的目標對象,目標對象也可以隨時進行替換。

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,967評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,273評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,870評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,742評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,527評論 6 407
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,010評論 1 322
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,108評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,250評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,769評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,656評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,853評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,371評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,103評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,472評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,717評論 1 281
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,487評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,815評論 2 372

推薦閱讀更多精彩內容