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阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容