策略模式的本质,也是设计模式的本质,是将易变化的部分分离出去,不管是对象和对象的行为分离,还是对象和对象表现分离等,都遵循。这是最基本的设计原则。然后把他们组合到一起,生成你需要的,不要管那么多设计原则,最终的目的是好维护,易读懂。
class Duck{ constructor(id){ = id; } getid(){ console.log(); }
display(){ console.log(“a nomal duck”); } }
class FlyBefavior{ constructor(wings){ this.wings = wings; } fly(){ console.log(fly with ${ this.wings}!
); } }
class QuackBefavior{ constructor(sound){ this.sound = sound; } quack(){ console.log(duck make sound,${this.sound}
); } }
class swimBefavior{ constructor(){
} swim(){ console.log(“duck swim in water.”); } }
class MallardDuck extends Duck{ constructor(id){ super(id); this.mallfly = new FlyBefavior(“green wings”); this.mallquack = new QuackBefavior(“gua gua gua”); }
fly(){ this.mallfly.fly(); }
quack(){ this.mallquack.quack() }
display(){ console.log(‘yee,a green head duck.’); } }
var m_duck = new MallardDuck(‘002’);
m_duck.display(); m_duck.getid(); m_duck.fly(); m_duck.quack();