今天来讲一下如何通过策略模式和工厂方法来消除累赘的if...else,具体什么是策略模式,大家可以自行百度学习,我就不再这里做过多的介绍了。
注意:如果业务场景简单,建议使用if...else,因为代码逻辑简单,便于理解
1.策略接口
1 /** 2 * 策略接口 3 * 4 */ 5 public interface Eat { 6 7 public void eatFruit(String fruit); 8 9 }
2.策略类
EatApple.java
1 /** 2 * 具体的策略类:吃苹果 3 */ 4 public class EatApple implements Eat{ 5 6 @Override 7 public void eatFruit(String fruit) { 8 System.out.println("吃苹果"); 9 } 10 11 }
EatBanana.java
1 /** 2 * 具体的策略类:吃香蕉 3 */ 4 public class EatBanana implements Eat { 5 6 @Override 7 public void eatFruit(String fruit) { 8 System.out.println("吃香蕉"); 9 } 10 11 }
EatPear.java
1 /** 2 * 具体的策略类:吃梨 3 */ 4 public class EatPear implements Eat { 5 6 @Override 7 public void eatFruit(String fruit) { 8 System.out.println("吃梨"); 9 } 10 11 }
3.策略上下文
1 /** 2 * 策略上下文 3 */ 4 public class EatContext { 5 6 private Eat eat; 7 8 public EatContext(Eat eat) { 9 this.eat = eat; 10 } 11 12 public void eatContext(String fruit) { 13 eat.eatFruit(fruit); 14 } 15 16 }
4.策略工厂类
1 /** 2 * 策略工厂类 3 */ 4 public class EatFactory { 5 6 private static Map<String, Eat> map = new HashMap<>(); 7 8 static { 9 map.put("apple", new EatApple()); 10 map.put("banana", new EatBanana()); 11 map.put("pear", new EatPear()); 12 } 13 14 public static Eat getEatStrategy(String fruitType) { 15 return map.get(fruitType); 16 } 17 }
5.测试
1 public class Demo { 2 3 public static void main(String[] args) { 4 String fruit = "apple"; 5 // 传入具体水果类型,得到苹果策略接口 6 Eat eat = EatFactory.getEatStrategy(fruit); 7 // 调用具体策略方法 8 eat.eatFruit(fruit); 9 } 10 }
测试结果:
吃苹果
第一次写博客,写的不好的地方,还望大家留言指教!