在Java中實現策略模式通常需要以下步驟:
public interface Strategy {
void execute();
}
public class ConcreteStrategyA implements Strategy {
@Override
public void execute() {
System.out.println("Executing strategy A");
}
}
public class ConcreteStrategyB implements Strategy {
@Override
public void execute() {
System.out.println("Executing strategy B");
}
}
public class Context {
private Strategy strategy;
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
public void executeStrategy() {
strategy.execute();
}
}
public class Main {
public static void main(String[] args) {
Context context = new Context();
Strategy strategyA = new ConcreteStrategyA();
context.setStrategy(strategyA);
context.executeStrategy();
Strategy strategyB = new ConcreteStrategyB();
context.setStrategy(strategyB);
context.executeStrategy();
}
}
通過以上步驟,我們就成功實現了策略模式的示例代碼。在實際應用中,可以根據具體的業務需求定義不同的策略和對應的具體策略類,并在上下文類中根據需要動態切換不同的策略。