策略模式的应用
2019-07-14 17:22
1581 查看
前言
在春招秋招之时,因为面试中会问到大量的设计模式。所以有去看一些关于设计模式的书籍,博客,等等。比如秦小波老师写的《设计模式之禅》。但当时仅限于看,包括现在也仅限于看。有的时候项目中,你都不知道有没有运用到了设计模式。也许用到了单例模式,但你并不知道如何用的,不知不觉就用到了。
当时并不知道设计模式怎么用,仅仅于看。最近毕业了,进公司实习了一周左右。大概都是在看项目代码中度过的,其中看到了一处特别熟悉的代码。这个代码就是策略者模式。写的非常的优雅,在此记录一下。
策略者模式
我个人简单理解,策略这模式就是代替if else的一种模式。
很简单的一个例子。比如人,人分为男人,女人,甚至不清楚性别的人。但这三种类型的人,都有不同的行为。那么我们在描述这些不同行为的时候,一般我们做法就是如下:
if (male) { //... } else if (female) { //... } else { //... }
类似如上。很多个if,else进行嵌套。这样非常的难看,不优雅。如果我们用策略这模式替换,会怎么样。
策略者模式例子
- 第一步定义一个person接口
public interface Person { void executeStrategy(); }
- 第二步定义person的继承类,如男人,女人等等
public class MalePerson implements Person { public void executeStrategy() { System.out.println("我是男性"); } } public class FemalePerson implements Person { public void executeStrategy() { System.out.println("我是女性"); } } public class UnknownPerson implements Person { public void executeStrategy() { System.out.println("未知性别"); } }
- 第三步定义一个enum类,表示可选择性。
@Getter public enum SexEnum { MALE("male", "男性"), FEMALE("female", "女性"), UNKNOWN("unknown", "未知"); private String code; private String sex; SexEnum(String code, String sex) { this.code = code; this.sex = sex; } }
- 最后一步定义一个策略选择器
public class ContextStrategy { private MalePerson malePerson = new MalePerson(); private FemalePerson femalePerson = new FemalePerson(); private UnknownPerson unknownPerson = new UnknownPerson(); public Person getPersonStrategy(SexEnum sexEnum) { if ("male".equals(sexEnum.getCode())) { return malePerson; } else if ("female".equals(sexEnum.getCode())) { return femalePerson; } else { return unknownPerson; } } }
- 最终测试如下:
public class Main { public static void main(String[] args) { ContextStrategy strategy = new ContextStrategy(); strategy.getPersonStrategy(SexEnum.MALE).executeStrategy(); strategy.getPersonStrategy(SexEnum.FEMALE).executeStrategy(); strategy.getPersonStrategy(SexEnum.UNKNOWN).executeStrategy(); } } // 结果如下: // 我是男性 // 我是女性 // 未知性别
其实我们可以看到。策略选择器是传入一个Enum类,然后根据传入Enum的不同,选择了不同的继承类。从而实现了if else。优雅的过渡。
可以看到,代码非常的优雅易懂,主代码,没有if else分支。但同时代码量多了起来。不过也很容易维护。
总的来说,利大于弊。
大致的图例如下:
相关文章推荐
- JAVA设计模式-策略模式应用实例
- JAVA设计模式-策略模式应用实例
- Spring 资源访问剖析和策略模式应用
- [策略模式]在游戏开发中的应用
- Spring 资源访问剖析和策略模式应用
- 设计模式实战应用之一:策略模式
- 策略模式和简单工厂及反射的联合应用(待续)
- 设计模式之策略模式在设计一群鸭子中的应用
- 策略模式在需求重构中的实际应用
- JAVA设计模式-策略模式应用实例
- 接口应用——策略模式
- Spring 资源访问剖析和策略模式应用
- Spring 资源访问剖析和策略模式应用
- 设计模式实战应用之一:策略模式
- 设计模式在 TypeScript 中的应用 - 策略模式
- 应用策略设计模式
- 转:Spring 资源访问剖析和策略模式应用
- JAVA设计模式-策略模式应用实例
- Spring 资源访问剖析和策略模式应用
- Spring 资源访问剖析和策略模式应用