策略模式
1 public interface Strategy { 2 3 void algorithmInterface(); 4 }
1 public class Context { 2 3 private Strategy strategy; 4 5 public Context(Strategy strategy){ 6 this.strategy = strategy; 7 } 8 9 public void uStrategy(){ 10 this.strategy.algorithmInterface(); 11 } 12 }
1 public class ConcreteStrategyA implements Strategy { 2 3 @Override 4 public void algorithmInterface() { 5 // TODO Auto-generated method stub 6 7 System.out.println("A Strategy works"); 8 } 9 10 }
1 public class ConcreteStrategyB implements Strategy { 2 3 @Override 4 public void algorithmInterface() { 5 // TODO Auto-generated method stub 6 7 System.out.println("B Strategy works"); 8 } 9 10 }
1 public class ConcreteStrategyC implements Strategy { 2 3 @Override 4 public void algorithmInterface() { 5 // TODO Auto-generated method stub 6 7 System.out.println("C Strategy works"); 8 } 9 10 }
设计基类Duck,子类MallarDuck,RedheadDuck,RubberDuck,duck can swim(),fly(),quack().
方法一:
很明显,rubberduck也会飞了,如果以后在增加鸭子类别,则需要重写fly,灵活性低,复用不当。
方法二:把变化的部分分离出来,即将fly放在接口中,会飞的鸭子继承这个借口,如图
如此一来破坏了复用性,每一种鸭子都需要实现fly(),不如方法一中直接继承的复用性强。
方法三:
面向接口
扩展了fly与quack的方式,使用接口的引用完成了变化的封装