策略模式
在策略模式(Strategy Pattern)中,一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。
public interface Strategy { public int operate(int num1, int num2); }
public class AddOperation implements Strategy { @Override public int operate(int num1, int num2) { return num1 + num2; } }
public class MultiplyOperation implements Strategy { @Override public int operate(int num1, int num2) { return num1 * num2; } }
public class SubtractOperation implements Strategy { @Override public int operate(int num1, int num2) { return num1 - num2; } }
public class Context { private Strategy strategy; public Context(Strategy strategy) { this.strategy = strategy; } public int execute(int num1, int num2) { return strategy.operate(num1, num2); } }
测试:
public class TestDemo { public static void main(String[] args) { Context c1 = new Context(new AddOperation()); System.out.println(c1.execute(2,4)); Context c2 = new Context(new SubtractOperation()); System.out.println(c2.execute(2,4)); Context c3 = new Context(new MultiplyOperation()); System.out.println(c3.execute(2,4)); } }
结果:
能看到,算法的改变因newContext的构造方法不同而改变。 它不在编译时候确定,而是运行时候确定算法。