Sometimes when I look at the world, I can see a line behind it.

Strategy pattern

In computerprogramming, the strategypattern (also known asthe policy pattern) is aparticular softwaredesign pattern, whereby algorithms canbe selected at runtime.

The strategy pattern is intended to provide a means to define afamily of algorithms, encapsulate each one as an object, and makethem interchangeable. The strategy pattern lets the algorithms varyindependently from clients that use them.



The Wikibook ComputerScience Design Patterns has a page on the topicof

Strategyimplementations in various languages

The following exampleis in Java.

//StrategyExampletest application 

class StrategyExample{ 

   public static void main(String[] args){ 


       // Threecontexts following different strategies

       context =new Context(new ConcreteStrategyAdd());

       int resultA= context.executeStrategy(3,4);

       context =new Context(new ConcreteStrategySubtract());

       int resultB= context.executeStrategy(3,4); 

       context =new Context(new ConcreteStrategyMultiply());

       int resultC= context.executeStrategy(3,4);




// The classes thatimplement a concrete strategy should implementthis 

// The context classuses this to call the concrete strategy

interface Strategy{

   int execute(int a, intb); 


// Implements thealgorithm using the strategy interface

classConcreteStrategyAdd implements Strategy { 

   public int execute(int a, int b){

      System.out.println("Called ConcreteStrategyAdd'sexecute()");

       return a +b;  // Do an addition with a andb



classConcreteStrategySubtract implements Strategy{ 

   public int execute(int a, int b){

      System.out.println("CalledConcreteStrategySubtract's execute()");

       return a -b;  // Do a subtraction with a andb



classConcreteStrategyMultiply implements Strategy{ 

   public int execute(int a, int b){

      System.out.println("CalledConcreteStrategyMultiply's execute()");

       return a *b;   // Do a multiplication with a andb



// Configured with aConcreteStrategy object and maintains a reference to a Strategyobject

class Context{ 

   private Strategystrategy; 

   // Constructor

   public Context(Strategy strategy){

      this.strategy = strategy;



   public int executeStrategy(int a, int b){

       returnstrategy.execute(a, b);




个人分类: 其他技术
想对作者说点什么? 我来说一句