java设计模式之策略模式

// 策略接口 public interface Strategy { void execute(); } // 具体策略类A public class ConcreteStrategyA implements Strategy { @Override public void execute() { System.out.println("Executing strategy A"); } } // 具体策略类B public class ConcreteStrategyB implements Strategy { @Override public void execute() { System.out.println("Executing strategy B"); } } // 上下文类 public class Context { private Strategy strategy; public Context(Strategy strategy) { this.strategy = strategy; } public void setStrategy(Strategy strategy) { this.strategy = strategy; } public void executeStrategy() { strategy.execute(); } } // 客户端代码 public class Client { public static void main(String[] args) { Context context = new Context(new ConcreteStrategyA()); context.executeStrategy(); // 执行策略A context.setStrategy(new ConcreteStrategyB()); context.executeStrategy(); // 执行策略B } }
上一篇:『玩转Streamlit』--登录认证机制


下一篇:【Web自动化】探索Selenium与WebDriver的核心原理