【混合模式】策略模式+工厂模式+模板方法

Author:Zhu Yuan
航空宇航制造工程 工科男
比昨天的我更强
CSDN@weixin_44632389
if和else嵌套
策略模式+工厂模式

传统方法:每人都用if和else使代码冗余,而且需求方一旦改变需求,每人都要改动判断条件
策略模式+工厂模式+模板方法:由一人专门负责与需求方沟通和更改条件,把任务模块化并对外提供API,其余人只需要调用API

案例一:条件无返回值

输出接口

public interface Handle {
   
    void output();
}

阿斗类
根据需求向工厂内注册条件,把调用方传来的参数传进工厂拿出结果

public class ADou{
   
    public void begin(String height){
   
        new FiveMetersHandle().afterPropertiesSet();
        new TenMetersHandle().afterPropertiesSet();
        new FifteenMetersHandle().afterPropertiesSet();
        new TwentyMetersHandle().afterPropertiesSet();
        new TwentyFiveMetersHandle().afterPropertiesSet();
        Handle invokeStrategy=Factory.getInvokeStrategy(height);
        invokeStrategy.output();
    }
}

工厂类
用hashmap储存条件,根据参数返回指定条件

class Factory{
   
    private static Map<String, Handle> strategyMap=new HashMap<>();
    public static Handle getInvokeStrategy(String str){
   
        return strategyMap.get(str);
    }
    public static void 
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值