java设计模式之行为型模式-策略模式
2016-04-30 19:51
441 查看
策略设计模式
策略模式,指对象有某个行为,但是在不同的场景中,该行为有不同的实现算法。比如每个人都要“交个人所得税”,但是“在美国交个人所得税”和“在中国交个人所得税”就有不同的算税方法。定义了一族算法(业务规则);
封装了每个算法,算法之间在客户端是各自独立的;
这族的算法可互换代替(interchangeable)。
适用性
许多相关类仅仅是行为不同。需要使用一个算法的不同实现。
算法使用了客户不应该知道的数据。策略模式可以避免暴露复杂的、与算法相关的数据结构。
一个类定义了很多行为,而且这些行为在这个类里的操作以多个条件语句的形式出现。策略模式将相关的条件分支移入它们各自的 Strategy 类中以代替这些条件语句。
UML
例子
首先定义策略接口:/**
* 一个具体的策略应该实现该接口,并且一个上下文对象Context应该持有该接口的引用
* @author dengfengdecao
*
*/
public interface Strategy {
void execute();
}
该接口定义了一个抽象的算法。
有了策略接口,接下来就是一个个具体的策略了:
public class FirstStrategy implements Strategy {
public void execute() {
// 在这里实现具体得算法策略
System.out.println("Called FirstStrategy.execute()");
}
}
public class SecondStrategy implements Strategy {
public void execute() {
// 在这里实现具体得算法策略
System.out.println("Called SecondStrategy.execute()");
}
}
public class ThirdStrategy implements Strategy {
public void execute() {
// 在这里实现具体得算法策略
System.out.println("Called ThirdStrategy.execute()");
}
}
以上定义了三个具体策略。接下来需要一个上下文对象:
/**
* 配置具体的策略并持有一个Strategy接口的引用
* @author dengfengdecao
*
*/
public class Context {
Strategy strategy;
public Context(Strategy strategy) {
super();
this.strategy = strategy;
}
public void execute() {
this.strategy.execute();
}
}
在这个对象里,引用了策略接口,并定义了一个构造函数来传递具体的策略对象。
最后在客户端测试:
public class StrategyClient {
public static void main(String[] args) {
Context context;
// 以下运行三个不同的策略
context = new Context(new FirstStrategy());
context.execute();
context = new Context(new SecondStrategy());
context.execute();
context = new Context(new ThirdStrategy());
context.execute();
}
}
结果:
一个更具体的例子可参考此文:http://blog.csdn.net/defonds/article/details/16832081
相关文章推荐
- 【Struts】:Struts1和Struts2的区别与联系
- String.intern in Java 6, 7 and 8 – string pooling (在Java 6,7和8中的String.intern - 字符串常量池化)
- Java——异常处理
- 第十章 springboot + logback
- Java集合类操作优化经验总结
- struts配置
- RxJava过滤操作符
- Struts2.相关异常处理
- Java循环练习:100~200之间有哪些数是质数?
- java基础:在子类的构造函数中为什么必须调用父类的构造函数(与转型)
- JAVA中的sort排序
- java定时器的使用
- Java中Runnable和Thread的区别
- Hadoop概念学习系列之hadoop Java API、 hadoop Streaming 、hadoop Pipes 三者比较学习(十九)
- jps -- java 进程查看命令
- Java并发编程--CountDownLatch配合线程池
- Java循环练习:打印图案-6
- Head First Java设计模式思维导图总结
- java之Math类的一些用法
- JavaSE入门学习34:Java集合框架之Collection接口、子接口及其实现类