Java设计模式——策略模式
2016-06-26 10:57
721 查看
策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户
而独立变化。(原文:The Strategy Pattern defines a family of algorithms,encapsulates each one,and makes them
interchangeable. Strategy lets the algorithm vary independently from clients that use it.)
一般的,策略模式主要分为以下三个角色:
1. 环境角色(Context):持有一个策略类引用
2. 抽象策略(Strategy):定义了多个具体策略的公共接口,具体策略类中各种不同的算法以不同的方式实现这个接口;Context
使用这些接口调用不同实现的算法。一般的,我们使用接口或抽象类实现。
3. 具体策略(ConcreteStrategy):实现抽象策略类中的相关的算法或操作。
标准接口:
Ps:
策略模式偏向于对实现方法或策略的封装,调用者不需要考虑具体实现,只要指定使用的策略即可。
装饰器模式一般用于需要对功能进行扩展的场合,每一种装饰都是一种扩展或增强。
而独立变化。(原文:The Strategy Pattern defines a family of algorithms,encapsulates each one,and makes them
interchangeable. Strategy lets the algorithm vary independently from clients that use it.)
一般的,策略模式主要分为以下三个角色:
1. 环境角色(Context):持有一个策略类引用
2. 抽象策略(Strategy):定义了多个具体策略的公共接口,具体策略类中各种不同的算法以不同的方式实现这个接口;Context
使用这些接口调用不同实现的算法。一般的,我们使用接口或抽象类实现。
3. 具体策略(ConcreteStrategy):实现抽象策略类中的相关的算法或操作。
标准接口:
public interface IStrategy { public void exeStrategy(); }策略1:
public class Strategy1 implements IStrategy { @Override public void exeStrategy() { // TODO Auto-generated method stub System.out.println("This is the first Strategy."); } }策略2:
public class Strategy2 implements IStrategy { @Override public void exeStrategy() { // TODO Auto-generated method stub System.out.println("This is the second strategy"); } }Context类:持有一个策略对象
public class Holder { private IStrategy iStrategy; public Holder(IStrategy iStrategy) { this.iStrategy = iStrategy; } public void operate(){ this.iStrategy.exeStrategy(); } }测试类:
public class HolderTest { @Test public void testOperate() { Holder holder = new Holder(new Strategy1()); holder.operate(); } }
Ps:
策略模式偏向于对实现方法或策略的封装,调用者不需要考虑具体实现,只要指定使用的策略即可。
装饰器模式一般用于需要对功能进行扩展的场合,每一种装饰都是一种扩展或增强。
相关文章推荐
- JAVA中的注解(Annotation)
- javac 和 java命令
- 日常小结-java何时抛出异常
- JAVA编程解析之classpath的深入理解
- JDBC的入门
- Java内存模型与对象的探秘
- 深入理解JAVA集合系列四:ArrayList源码解读
- 华为机试---血型遗传检测
- java可视化编程 eclipse安装windowBuilder插件
- java基础(五)面向对象/类/对象/形式参数/局部和成员变量
- eclipse字体 osgi错误Could not find bundle: org.eclipse.equinox.console
- 【java多线程系列】java内存模型与指令重排序
- 【java多线程系列】java内存模型与指令重排序
- eclipse 全文搜索查找字符串
- Struts2访问Servlet API的3种方式
- Java起步
- java 用户、角色、权限数据库设计
- jbpm和spring、hibernate的集成
- Java千百问_08JDK详解(012)_JPDA是什么
- java web简单权限管理设计