在设计模式中,有一种常见的解决方案是使用策略模式(Strategy Pattern)来避免不必要地添加抽象函数以适应新功能。策略模式通过将算法封装在不同的策略类中,使得算法可以独立于客户端的变化而变化。
下面是一个使用策略模式的示例代码:
// 定义一个抽象策略接口
interface Strategy {
void execute();
}
// 实现具体的策略类
class ConcreteStrategyA implements Strategy {
@Override
public void execute() {
System.out.println("执行策略A");
}
}
class ConcreteStrategyB implements Strategy {
@Override
public void execute() {
System.out.println("执行策略B");
}
}
// 定义一个上下文类,用于切换策略
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 Main {
public static void main(String[] args) {
// 创建上下文对象,并设置初始策略为A
Context context = new Context(new ConcreteStrategyA());
// 执行策略A
context.executeStrategy();
// 切换策略为B
context.setStrategy(new ConcreteStrategyB());
// 执行策略B
context.executeStrategy();
}
}
在这个示例中,抽象策略接口 Strategy
定义了一个 execute()
方法,具体的策略类 ConcreteStrategyA
和 ConcreteStrategyB
分别实现了这个接口。上下文类 Context
用于切换策略,并在执行策略时调用对应的 execute()
方法。
使用策略模式,当需要添加新的功能时,我们只需要创建一个新的具体策略类并实现 Strategy
接口即可,而无需修改已有的代码。这样就避免了不必要地添加抽象函数以适应新功能的问题。
上一篇:避免不必要的字符串替换