设计模式之策略模式
Strategy模式也叫作策略模式时行为模式之一,它对一系列的算法加以封装,为所有算法定义一个抽象的算法接口,并通过继承该抽象算法接口对所有的算法加以封装和实现,具体的算法选择交由客户端决定(策略)。Strategy模式主要用俩平滑地处理算法的切换。
抽象接口Strategy:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.Design.Strategy; 2 3 public interface Strategy { 4 5 //加密 6 public void encrypt(); 7 8 9 10 }
具体实现类StrategyA:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.Design.Strategy; 2 3 public class MD5Strategy implements Strategy { 4 5 @Override 6 public void encrypt() { 7 System.out.println("MD5加密"); 8 9 } 10 11 }
具体实现类StrategyB:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.Design.Strategy; 2 3 public class MDSStrategy implements Strategy { 4 5 @Override 6 public void encrypt() { 7 System.out.println("执行MDS加密"); 8 } 9 10 }
持有Strategy引用的Context:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.Design.Strategy; 2 3 public class Context { 4 5 private Strategy stragegy; 6 7 public Context(Strategy stragegy) { 8 this.stragegy = stragegy; 9 } 10 11 public void encrypt(){ 12 this.stragegy.encrypt(); 13 } 14 15 16 }
策略模式比装饰者模式简单。