在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();
}
}
通过以上步骤,我们就成功实现了策略模式的示例代码。在实际应用中,可以根据具体的业务需求定义不同的策略和对应的具体策略类,并在上下文类中根据需要动态切换不同的策略。