设计模式课时十六------策略模式之场景剖析

解决平级if else 的杀手锏

注:if判断的条件单一且符合条件后处理简单,简易使用switch

二话不说上代码:
首先是简单的模式

interface IStrategy {
    boolean isAccept(int type);
    void process();
}

class StrategyFruitImpl implements IStrategy {


    @Override
    public boolean isAccept(int type) {
        return type == 1 ? true : false;
    }

    @Override
    public void process() {
        //  do  fruit code
    }
}

class StrategrVegetables implements IStrategy {

    @Override
    public boolean isAccept(int type) {
        return type == 2 ? true : false;
    }

    @Override
    public void process() {
        //  ...do vegetables
    }
}

最重要的用法:

import java.util.ArrayList;
import java.util.List;

public class Strategy {

    private  static  List<IStrategy> strategyList = prepare();

    public static void main(String[] args) {

        int type = 1;
        doStrategyProcess(type);
    }

    /**
     * 如果使用Spring,可以使用DI一键注入
     * @return
     */
    private static List<IStrategy> prepare(){
        List<IStrategy> strategyList = new ArrayList<>();
        strategyList.add(new StrategyFruitImpl());
        strategyList.add(new StrategrVegetables());
        return  strategyList;
    }

    /**
     * 根据 传参 处理自己关注的 类型
     * @param type
     */
    private static void doStrategyProcess(int type){
        for (IStrategy item : strategyList) {
            if (item.isAccept(type)) {
                item.process();
            }
        }
    }

}

原创不易,欢迎来赞

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值