23种设计模式之策略模式

策略模式

该模式定义了一系列算法,并将每个算法封装起来,使它们可以相互替换,且算法的变化不会影响使用算法的客户。
以做鱼为例,可以做红烧鱼,水煮鱼,通过环境指定某一种鱼,具体做法由抽象类的实现类来做,且可以随意替换。

public class CategoryTest {
    public static void main(String[] args) {
        Fish hotFish = new HotFish();
        Fish redCookedFish = new RedCookedFish();

        // 做水煮鱼
        CookContext cookContext = new CookContext();
        cookContext.setFish(hotFish);
        cookContext.cooke();
        System.out.println("----------------------------");
        // 做红烧鱼
        cookContext.setFish(redCookedFish);
        cookContext.cooke();


    }
}

interface Fish{
    void cook();
}
class HotFish implements Fish{

    @Override
    public void cook() {
        System.out.println("做水煮鱼");
    }
}
class RedCookedFish implements Fish{

    @Override
    public void cook() {
        System.out.println("做红烧鱼鱼");
    }
}
class CookContext {
    private Fish fish;

    public Fish getFish() {
        return fish;
    }

    public void setFish(Fish fish) {
        this.fish = fish;
    }

    void cooke(){
        this.fish.cook();
    }
}

在这里插入图片描述

参考资料:
1.http://c.biancheng.net/view/1378.html
代码地址:https://gitee.com/zhoujie1/design-mode-and-principle.git

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值