//守护勋章策略实现类 public class GuardMedalServiceImpl implements IMedalService { @Override public void showMedal() { System.out.println("展示守护勋章"); } } //嘉宾勋章策略实现类 public class GuestMedalServiceImpl implements IMedalService { @Override public void showMedal() { System.out.println("嘉宾勋章"); } } //VIP勋章策略实现类 public class VipMedalServiceImpl implements IMedalService { @Override public void showMedal() { System.out.println("会员勋章"); } }
接下来,我们再定义策略工厂类,用来管理这些勋章实现策略类,如下:
1 2 3 4 5 6 7 8 9 10 11 12
//勋章服务工产类 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); } }
使用了策略+工厂模式之后,代码变得简洁多了,如下:
1 2 3 4 5 6 7
public class Test { public static void main(String[] args) { String medalType = "guest"; IMedalService medalService = MedalServicesFactory.getMedalService(medalType); medalService.showMedal(); } }