java中23种设计模式之2-策略模式(strategy pattern)
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.
策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。
组成:
—抽象策略角色: 策略类,通常由一个接口或者抽象类实现。
interface IStrategy
{
void algorithm();
}
class StrategyA implements IStrategy
{
public void algorithm()
{
System.out.println("this is a StrategyA`s algorithm");
}
}
class StrategyB implements IStrategy
{
public void algorithm()
{
System.out.println("this is a StrategyB`s algorithm");
}
}
class Context
{
private IStrategy aIStrategy=null;
public Context(IStrategy tmpIStrategy)
{
aIStrategy=tmpIStrategy;
}
public void doAlgorithm()
{
aIStrategy.algorithm();
}
}
public class StrategyPatternTest
{
public static void main(String[] args)
{
Context aContext=new Context(new StrategyA());
aContext.doAlgorithm();
aContext=new Context(new StrategyB());
aContext.doAlgorithm();
}
}
//////////////////////////////////////////////////////////
输出结果:
this is a StrategyA`s algorithm
this is a StrategyB`s algorithm
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。