java - 设计模式 - Strategy and Bridge (Overlap in design)

标签 java oop design-patterns

今天,我的困境来自于试图理解为什么在实现战略模式和桥接模式方面存在重叠。

桥接模式(从抽象中抽象实现)

// 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/

相关文章:

java - Mockito "thenThrow"没有按预期抛出异常

c++ - 在 C++ 中如何从友元函数访问私有(private)函数?

.net - 什么对象应该从数据访问层返回到业务层一个n层系统

java - 在测试类之前和之后使 ApplicationContext 变脏

java - 接口(interface)真的没有构造函数吗?

c++ - 成员模板函数指针错误

c# - 如果覆盖它,是否要求子类调用 super.doSomething()?

android - OpenGL ES 和线程结构

python - 如何使用 Python 创建单例?

java - HttpURLConnection 无效的 HTTP 方法 : PATCH