本文主要是介绍策略模式+工厂方法消除if else,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
假设需求为,根据不同勋章类型,处理相对应的勋章服务,优化前有以下代码:
String medalType = "guest";if ("guest".equals(medalType)) {System.out.println("嘉宾勋章");} else if ("vip".equals(medalType)) {System.out.println("会员勋章");} else if ("guard".equals(medalType)) {System.out.println("展示守护勋章");}...
首先,我们把每个条件逻辑代码块,抽象成一个公共的接口,可以得到以下代码:
//勋章接口
public interface IMedalService {void showMedal();String getMedalType();
}
我们根据每个逻辑条件,定义相对应的策略实现类,可得以下代码:
//守护勋章策略实现类
public class GuardMedalServiceImpl implements IMedalService {@Overridepublic void showMedal() {System.out.println("展示守护勋章");}@Overridepublic String getMedalType() {return "guard";}
}
//嘉宾勋章策略实现类
public class GuestMedalServiceImpl implements IMedalService {@Overridepublic void showMedal() {System.out.println("嘉宾勋章");}@Overridepublic String getMedalType() {return "guest";}
}
//VIP勋章策略实现类
public class VipMedalServiceImpl implements IMedalService {@Overridepublic void showMedal() {System.out.println("会员勋章");}@Overridepublic String getMedalType() {return "vip";}
}
接下来,我们再定义策略工厂类,用来管理这些勋章实现策略类,如下:
//勋章服务工产类
public class MedalServicesFactory {private static final Map<String, IMedalService> map = new HashMap<>();static {map.put("guard", new GuardMedalServiceImpl());map.put("vip", new VipMedalServiceImpl());map.put("guest", new GuestMedalServiceImpl());}public static IMedalService getMedalService(String medalType) {return map.get(medalType);}
}
使用了策略+工厂模式之后,代码变得简洁多了,如下:
public class Test {public static void main(String[] args) {String medalType = "guest";IMedalService medalService = MedalServicesFactory.getMedalService(medalType);medalService.showMedal();}
}
这篇关于策略模式+工厂方法消除if else的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!