策略模式

策略模式是一种设计模式,它将算法族封装起来,允许算法独立于使用它的客户端进行变化。通过对象之间的多态性,策略模式允许在运行时选择不同的算法,例如在鸭子类中,可以灵活地替换飞行和游泳行为。这种模式可以有效地减少大量组合的类数量,只需实现所需的行为对象。核心原则包括封装变化、多用组合少用继承以及针对接口编程。
摘要由CSDN通过智能技术生成

策略模式

策略模式

1.策略模式,
定义算法族,分别封装起来, 让它们之间可以互相替换, 此模式让算法的变化独立于使用算法的客户端。

class Duck{
    constructor(opts){
        this.name = opts.name || "";
        this.sex = opts.sex || "";
        this.flyBehavi = opts.flyer;
        this.swimBehavi = opts.swimer;
    }

    fly(){
        this.flyBehavi.fly();
    }

    swim(){
        this.swimBehavi.swim();
    }
}

class Flyer{
    fly(){
        console.info("i am flyer");
    }
}

class Swimer{
    swim(){
        console.info("i am swimer");
    }
}

class NewDuck extends Duck{
    constructor(opts){
        super(opts);
        this.name = opts.name;
    }
}

class NoFlyer extends Flyer{
    fly(){
        console.info("i can not fly");
    }
}

let a = new NewDuck({name:"哈哈", flyer:new NoFlyer(), swimer:new Swimer()});
a.fly();
a.swim();

简单来说,就是每次调用对象的方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值