There is no such thing as perfect programming, but we shouldn’t be discouraged because programming is a constant pursuit of perfection.

  1. The intent is to define a set of algorithms, encapsulate them one by one, and interchangeable with each other.
  2. The class diagram

  3. The instance
Interface Strategy {/** * operation * @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); }}Copy the code
  1. test
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);
    }
Copy the code

Running results:

plus strategy : 5
multiply strategy : 6
Copy the code

Want to see more? Please visit:Design patterns