什么是策略模式(Strategy)?

99 阅读1分钟

世界上并没有完美的程序,但是我们并不因此而沮丧,因为写程序就是一个不断追求完美的过程。

  1. 意图
    定义一系列算法,把它们一个个封装起来,并且可以相互替换。
  2. 类图
    在这里插入图片描述
  3. 实例
interface Strategy {
        /**
         * 操作
         * @param a
         * @param b
         */
        Integer option (Integer a, Integer b);
    }

    static class PlusStrategy implements Strategy {
        @Override
        public Integer option(Integer a, Integer b) {
            return a + b;
        }
    }

    static class MultiplyStrategy implements Strategy {
        @Override
        public Integer option(Integer a, Integer b) {
            return a * b;
        }
    }

    static class Context {
        private Strategy strategy;
        public Context (Strategy strategy) {
            this.strategy = strategy;
        }

        public Integer option (Integer a, Integer b) {
            return strategy.option(a, b);
        }
    }
  1. 测试
public static void main(String[] args) {
        Context ctx = new Context(new PlusStrategy());
        int re = ctx.option(3, 2);
        System.out.println("plus strategy : " + re);
        ctx = new Context(new MultiplyStrategy());
        re = ctx.option(3, 2);
        System.out.println("multiply strategy : " + re);
    }

运行结果:

plus strategy : 5
multiply strategy : 6

想看更多吗?请访问:设计模式