Author:Zhu Yuan
航空宇航制造工程 工科男
比昨天的我更强
CSDN@weixin_44632389
传统方法:每人都用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