TypeScript策略模式

// 策略模式  每个算法都封装起来。可以互换。

interface Stategy {

    do1:(  )=> void; 

}

//具体的构件

class aaa implements Stategy {

    do1() {

        YBLog.log("Test", " 策略具体做 1 ");

    }

}

//具体的构件

class bbb implements Stategy {

    do1() {

        YBLog.log("Test", " 策略具体做 2 ");

    }

}


 

//具体的装饰

class shiyongzhe {

    private stategy = null;

    setStategy(stategy: Stategy) {

        this.stategy = stategy;

    }

    doSomething()

    {

        this.stategy.do1(); 

    }

}

let cobj: shiyongzhe = new shiyongzhe();

let bb  = new aaa( );   

let aa  = new bbb( ); 

cobj.setStategy(bb);

cobj.doSomething();

//优点:自由切换。 减少多重判断。 容易扩展

//缺点:每个策略一个类,就是很多类。 所有的策略都要暴露出来。

猜你喜欢

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