策略模式是一種行為型設計模式,它定義了一系列的算法,并將每個算法封裝起來,使它們可以相互替換。這樣就可以使算法的變化獨立于使用算法的客戶。
在Java中,策略模式的應用可以通過以下步驟實現:
public interface Strategy {
void execute();
}
public class ConcreteStrategyA implements Strategy {
@Override
public void execute() {
// 具體算法A的實現
}
}
public class ConcreteStrategyB implements Strategy {
@Override
public void execute() {
// 具體算法B的實現
}
}
public class ConcreteStrategyC implements Strategy {
@Override
public void execute() {
// 具體算法C的實現
}
}
public class Context {
private 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();
Strategy strategyA = new ConcreteStrategyA();
Strategy strategyB = new ConcreteStrategyB();
Strategy strategyC = new ConcreteStrategyC();
context.setStrategy(strategyA);
context.executeStrategy();
context.setStrategy(strategyB);
context.executeStrategy();
context.setStrategy(strategyC);
context.executeStrategy();
}
}
在這個例子中,策略模式允許客戶根據需要選擇不同的具體策略,并且可以靈活地替換或添加新的策略,而不會影響到客戶代碼的其他部分。