策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户
而独立变化。(原文: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();
}
}
策略模式偏向于对实现方法或策略的封装,调用者不需要考虑具体实现,只要指定使用的策略即可。
装饰器模式一般用于需要对功能进行扩展的场合,每一种装饰都是一种扩展或增强。