策略模式:定义一系列算法,将它们分别封装起来,让他们之间可以相互替换,但不会影响到使用算法的用户。
public interface Strategy { public void function();}public class ConcreteStrategyOne implements Strategy{ @Override public void function() { System.out.println("One."); }}public class ConcreteStrategyTwo implements Strategy{ @Override public void function() { System.out.println("Two."); }}
public class StrategyContext { private Strategy strategy; public StrategyContext(Strategy strategy) { this.strategy = strategy; } public void StrategyContextFunction() { strategy.function(); }}
public class StrategyDemo { public static void main(String[] args) { StrategyContext contextOne = new StrategyContext(new ConcreteStrategyOne()); contextOne.StrategyContextFunction(); StrategyContext contextTwo = new StrategyContext(new ConcreteStrategyTwo()); contextTwo.StrategyContextFunction(); }}