今天,我的困境来自于试图理解为什么在实现战略模式和桥接模式方面存在重叠。
桥接模式(从抽象中抽象实现)
// 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);
}
}
现在这里是策略模式——一个类的行为或其算法可以在运行时改变。计算器会将其操作委托(delegate)给策略
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);
}
}
这两种模式都涉及丢弃封装功能的策略对象。请帮助明确桥接模式(结构)和策略模式(行为)之间的区别。我的另一个困惑是,它们属于不同的知识范畴。
最佳答案
在您的示例中,我发现这两种模式之间存在一些重叠。
在第一种情况下,当我们需要将抽象与其实现分离以便两者可以独立变化时,使用桥接模式。 仅此而已,您只是在抽象实现。
在第二种情况下,策略类的行为可以在运行时改变。这也意味着对于具体的 Strategy 类,您也可以实现桥接模式,也许您正在使用一个类并希望将其分解。
关于java - 设计模式 - Strategy and Bridge (Overlap in design),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43910654/