TypeScript命令模式

abstract class command {

    protected receiver: Receiver = null;

    constructor(receiver: Receiver) {

        YBLog.log("Test", " 父类的构造函数 ");

        this.receiver = receiver

    }

    abstract excute(): void; // 必须在派生类中实现   

}

abstract class Receiver {

    abstract dos(): void; // 必须在派生类中实现     

}

class Receiver1 extends Receiver {

    dos() {

        YBLog.log("Test", " 我是接受者1 ,我做苦力 ");

    }

}

class Receiver2 extends Receiver {

    dos() {

        YBLog.log("Test", " 我是接受者2 ,我做苦力 ");

    }

}

class ommandA extends command {

    constructor() {

        YBLog.log("Test", " ommandA 构造函数 ");

        super(new Receiver1());

    }

    excute() {

        this.receiver.dos();

    }

}

class ommandB extends command {

    constructor() {

        YBLog.log("Test", " ommandB 构造函数 ");

        super(new Receiver2());

    }

    excute() {

        this.receiver.dos();

    }

}

//调用者 

class Invoker {

    private _command: command = null;

    public setCommand(value: command) {

        YBLog.log("Test", " 58 接受到命令");

        this._command = value;

    }

    public InitiateCall() {

        YBLog.log("Test", " 61 执行命令");

        this._command.excute()

    }

}

let invoker:Invoker = new Invoker();

let comma:ommandA = new ommandA();

let commb:ommandB = new ommandB();

invoker.setCommand(comma); //设置命令

invoker.InitiateCall(); //执行

invoker.setCommand(commb);

invoker.InitiateCall();

/**

Test  ommandA 构造函数 

Test  父类的构造函数 

Test  ommandB 构造函数 

Test  父类的构造函数 

Test  58 接受到命令

Test  61 执行命令

Test  我是接受者1 ,我做苦力 

Test  58 接受到命令

Test  61 执行命令

Test  我是接受者2 ,我做苦力 

**/

一优点: 解耦   调用者  与  具体的接受者没有 依赖。 功能扩展容易 。

二缺点: 命令会有N个 。

猜你喜欢

转载自blog.csdn.net/ting100/article/details/108683474