public class 策略模式 { public static void main(String[] args) { Strategy add=new ConcreteStrategyA(); Strategy sub=new ConcreteStrategyB(); Strategy multiply=new ConcreteStrategyC(); OperationContext context=new OperationContext(add); context.Operation(4,5); context=new OperationContext(sub); context.Operation(4,5); context=new OperationContext(multiply); context.Operation(4,5); } } class OperationContext{ Strategy strategy; public OperationContext(Strategy strategy) { this.strategy=strategy; } public void Operation(int a,int b){ strategy.TwoNumberOperation(a,b); } } interface Strategy{ public void TwoNumberOperation(int a,int b); } class ConcreteStrategyA implements Strategy{ @Override public void TwoNumberOperation(int a,int b) { System.out.println(a+b); } } class ConcreteStrategyB implements Strategy{ @Override public void TwoNumberOperation(int a,int b) { System.out.println(a-b); } } class ConcreteStrategyC implements Strategy{ @Override public void TwoNumberOperation(int a,int b) { System.out.println(a*b); } }
运算结果
标签:OperationContext,策略,int,void,模式,Strategy,new,设计模式,public From: https://www.cnblogs.com/cinan/p/17801113.html