2017-05-11 64 views
6

今天我的困境来自于试图理解为什么在策略和桥梁模式可以实施时存在重叠的原因。设计模式 - 策略与桥梁(重叠设计)

下面是桥接模式(从抽象的抽象实现)

// 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); 
    } 
} 

这两种模式都涉及丢弃封装功能的策略对象。请帮助Bridge模式(结构)和策略模式(行为)之间的明显差异。我遇到的另一个困惑是他们在不同的知识雨伞下。

+1

可能的[策略与桥接模式]重复(http://stackoverflow.com/questions/5863530/strategy-vs-bridge-patterns) –

+1

http://stackoverflow.com/questions/5863530/strategy-vs -bridge-patterns,http://stackoverflow.com/questions/464524/what-is-the-difference-between-the-bridge-pattern-and-the-strategy-pattern – Andrew

+0

策略是行为模式,Bridge是结构模式。看看http://stackoverflow.com/questions/464524/what-is-the-difference-between-the-bridge-pattern-and-the-strategy-pattern –

回答

1

策略模式表示您可以稍后更改核心算法。例如,当您编写电子商务应用程序时,您有B2B和B2C客户,这些客户有不同的付款和订购方式。然后,您将使用策略模式作为结帐策略。所以基本的行动是一样的,但两个用户使用不同的方式(策略)来实现。相反,桥梁模式表示您在两个模块之间建立了桥梁,您可以独立更换这些模块。这是针对抽象和信息隐藏。

3

在你的例子中,我看到这两个模式之间有一点重叠。

在第一种情况下,当我们需要将抽象与其实现分离时,使用Bridge模式,以使两者可以独立变化。 就是这样,你只是在抽象实现。

在第二种情况下,可以在运行时更改类行为。这也意味着进入一个具体的策略类,你也可以实现一个桥梁模式,也许你正在使用一个类,并希望去实现它。

0

该网桥用于封装组件并暴露其他一些接口。当您使用具有您无法控制的生命周期的组件时,通常会使用桥接器。它限制了软件对实现桥接的依赖性。

当您有不同的可能算法来执行特定操作时,将使用策略模式,并且您不希望保持从一个切换到另一个的能力。