结合策略模式和HashMap摆脱if else

在代码中使用过多的if else进行逻辑判断比较影响阅读,更重要的是,如果增加或减少一种逻辑情况就需要修改if else的分支,维护性差。
if(type == 1) do1()
else if(type == 2) do2()
else...
if else逻辑两个关键点:1、是什么条件;2、做什么事
策略模式是通过接口抽象这一系列动作,提供统一的行为模式。用来解决做什么事。
map用来f封装条件,根据条件不同选择不同的实现类赋予接口。用来解决是什么条件。
那么上面那段代码可以变为:
// 抽象动作
interface do{ do(); }
class do1 implement do { do1() } // 实现do1
class do2 implement do { do2() } // 实现do2
// 封装条件
Map con = new HashMap
con.put(1, new do1())
con.put(2, new do2())
// 逻辑调用变为
do do = con.get(type);
do.do();

或者更完美一点可以结合下工厂模式:
doFactory {
    private static Map con = new HashMap();
    static {
        con.put(1, new do1());
        con.put(2, new do2());
    }
    public static do creator(type){  
        return con.get(type);
    }
}
// 逻辑调用变为
do do = doFactory.creator(type);
do.do();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值