今天我的困惑来自于尝试理解为什么策略模式和桥接模式的实现方式存在重叠。以下是桥接模式(从抽象中抽象出一个实现):
现在介绍策略模式 - 一个类的行为或算法可以在运行时更改。计算器将把其操作委托给策略。
// Shapes object structure will not be concerned how they draw themselves
public abstract class Shape {
protected DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI){
this.drawAPI = drawAPI;
}
// This could also be put in the subcla
public void draw() {
drawAPI.drawCircle(radius,x,y);
}
}
现在介绍策略模式 - 一个类的行为或算法可以在运行时更改。计算器将把其操作委托给策略。
public class Calculator{
private Strategy strategy;
public Calculator(Strategy strategy){
this.strategy = strategy;
}
public int executeStrategy(int num1, int num2){
return strategy.doOperation(num1, num2);
}
}
这两种模式都涉及到丢弃封装功能的策略对象。请帮忙清楚地区分桥接模式(结构型)和策略模式(行为型)。我感到困惑的另一个问题是它们属于知识的不同领域。
在桥接模式中,将抽象和实现分离,使它们可以独立变化。桥接模式可用于最初只有几个实现的情况下,以便通过添加新的实现进行扩展。策略模式则允许从一组算法中选择一个来完成特定任务。这两者之间的主要区别在于它们的目的:桥接模式旨在使抽象和实现分离,而策略模式旨在提供灵活性,并根据需要动态更改算法。