设计模式-策略模式
结构图:
实现:
1 abstract public class Strategy { 2 public void algrithmInterface() 3 { 4 } 5 }
1 public class StrategyA extends Strategy{ 2 3 @Override 4 public void algrithmInterface() { 5 super.algrithmInterface(); 6 System.out.println("算法A的实现"); 7 } 8 9 10 }
1 public class StrategyB extends Strategy{ 2 3 @Override 4 public void algrithmInterface() { 5 super.algrithmInterface(); 6 System.out.println("算法B的实现"); 7 } 8 9 10 }
1 public class Context { 2 3 private Strategy strategy; 4 5 public Context(Strategy strategy) { 6 super(); 7 this.strategy = strategy; 8 } 9 10 public void contextInterface() 11 { 12 strategy.algrithmInterface(); 13 } 14 15 public void setStrategy(Strategy s) 16 { 17 this.strategy = s; 18 } 19 }
1 public class Client { 2 public static void main(String[] args) 3 { 4 Context context = new Context(new StrategyA()); 5 context.contextInterface(); 6 7 context.setStrategy(new StrategyB()); 8 context.contextInterface(); 9 } 10 }
应用常用:
该模式封装了一系列算法,让它们而已相互替换,而不会影响到客户端的变化。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步