zoukankan      html  css  js  c++  java
  • 策略模式

    一个类的行为或其算法可以在运行期更改。众多算法相似的时候,使用if else引发过于复杂难以维护。

    策略接口:

    1 public interface Strategy {
    2 
    3     int operation(int a, int b);
    4 }

    不同的策略:

     1 public class OperationAdd implements Strategy {
     2 
     3     @Override
     4     public int operation(int a, int b) {
     5         return a + b;
     6     }
     7 }
     8 
     9 public class OperationSub implements Strategy {
    10 
    11     @Override
    12     public int operation(int a, int b) {
    13         return a - b;
    14     }
    15 }

    持有策略的上下文:

     1 public class Context {
     2 
     3     private Strategy strategy;
     4 
     5     public Context(Strategy strategy) {
     6         this.strategy = strategy;
     7     }
     8 
     9     public int executeStrategy(int a, int b) {
    10         return strategy.operation(a, b);
    11     }
    12 }

    测试类:

     1 public class Main {
     2 
     3     public static void main(String[] args) {
     4         Context context = new Context(new OperationAdd());
     5         System.out.println(context.executeStrategy(1, 2));
     6 
     7         context = new Context(new OperationSub());
     8         System.out.println(context.executeStrategy(5, 3));
     9     }
    10 }
  • 相关阅读:
    <span>和<div>标签的隐藏和显示切换
    重启svn
    Mac下配置apache
    iOS时间显示今天昨天
    关于UIPageViewController那些事
    关于plist文件的那些事
    Xcode调试LLDB
    Reveal安装
    静态初始化器
    Static简介
  • 原文地址:https://www.cnblogs.com/avalon-merlin/p/10521894.html
Copyright © 2011-2022 走看看