美文网首页
策略模式 示例

策略模式 示例

作者: 黑色海鸥 | 来源:发表于2019-10-23 15:32 被阅读0次

    策略模式

    创建一个接口

    public interface Strategy {
       public int doOperation(int num1, int num2);
    }
    

    创建实现接口的实体类。

    public class OperationAdd implements Strategy{
       @Override
       public int doOperation(int num1, int num2) {
          return num1 + num2;
       }
    }
    
    public class OperationSubstract implements Strategy{
       @Override
       public int doOperation(int num1, int num2) {
          return num1 - num2;
       }
    }
    
    public class OperationMultiply implements Strategy{
       @Override
       public int doOperation(int num1, int num2) {
          return num1 * num2;
       }
    }
    

    创建 Context

    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);
       }
    }
    

    使用 Context 来查看当它改变策略 Strategy 时的行为变化。

    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));
     
          context = new Context(new OperationMultiply());    
          System.out.println("10 * 5 = " + context.executeStrategy(10, 5));
       }
    }
    

    执行程序,输出结果

    10 + 5 = 15
    10 - 5 = 5
    10 * 5 = 50
    

    相关文章

      网友评论

          本文标题:策略模式 示例

          本文链接:https://www.haomeiwen.com/subject/xfskvctx.html