Strategy Pattern



  • Strategy Pattern

    There are common situations when classes differ only in their behavior. For this cases is a good idea to isolate the algorithms in separate classes in order to have the ability to select different algorithms at runtime.

    Intent

    • Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it.
    • Capture the abstraction in an interface, bury implementation details in derived classes.

    Implementation

    We are going to create a Strategy interface defining an action and concrete strategy classes implementing the Strategy interface. Context is a class which uses a Strategy.

    // Strategy.java
    public interface Strategy {
       public int doOperation(int num1, int num2);
    }
    
    // OperationAdd.java
    public class OperationAdd implements Strategy{
       @Override
       public int doOperation(int num1, int num2) {
          return num1 + num2;
       }
    }
    
    // OperationSubstract.java
    public class OperationSubstract implements Strategy{
       @Override
       public int doOperation(int num1, int num2) {
          return num1 - num2;
       }
    }
    
    // Context.java
    public class Context {
       private Strategy strategy;
    
       public Context(Strategy strategy){
          this.strategy = strategy;
       }
    
       public int executeStrategy(int num1, int num2){
          return strategy.doOperation(num1, num2);
       }
    }
    
    // StrategyPatternDemo.java
    public class StrategyPatternDemo {
       public static void main(String[] args) {
          Context context = new Context(new OperationAdd());
          System.out.println("10 + 5 = " + context.executeStrategy(10, 5));
    
          context = new Context(new OperationSubstract());
          System.out.println("10 - 5 = " + context.executeStrategy(10, 5));
       }
    }
    

    Reference

    TutorialsPoint


登录后回复
 

与 BitTiger Community 的连接断开,我们正在尝试重连,请耐心等待