【问题标题】:Using additional methods in the Decorator pattern在装饰器模式中使用附加方法
【发布时间】:2014-11-18 21:00:52
【问题描述】:

在 GoF 设计模式一书中关于装饰器模式的章节中,有一个带有 GUI 控件的示例。这是 C++ 中的示例代码(我稍作改动):

class VisualComponent
{
    public:
    virtual void Draw() = 0;
};

class TextView : public VisualComponent
{
    // ...
};

class Decorator : public VisualComponent
{
    private:
    VisualComponent * component;

    public:
    Decorator(VisualComponent * c)
        : component(c)
    {}
    virtual void Draw()
    {
        component->Draw();
    }
};

class ScrollDecorator : public Decorator
{
    public:
    ScrollDecorator(VisualComponent * c)
        : Decorator(c)
    {}
    virtual void Draw()
    {
        Decorator::Draw();
    }
    void ScrollTo()   // [1]
    {
        // perform scrolling
    }
};

class BorderDecorator : public Decorator
{
    private:
    void DrawBorder()   // [2]
    {
        // draw border
    }

    public:
    BorderDecorator(VisualComponent * c)
        : Decorator(c)
    {}
    virtual void Draw()
    {
        Decorator::Draw();
        DrawBorder();
    }
};

装饰器类的重点是向对象添加新的行为/外观/等等。例如:

VisualComponent myControl = new BorderDecorator(new ScrollDecorator(new TextView)));

创建一个可滚动且有边框的文本视图控件。添加边框对客户端是不可见的 - 它是一个私有方法 ([2]),它在 VisualComponent 接口的 Draw() 方法中调用。

然而,在示例中,作者还展示了(在图中)滚动 GUI 控件的方法 ([1])。现在,书中没有更多提及,所以我不知道该方法到底应该做什么或应该如何表现。最重要的是,我不知道它是公共的(以及类接口的一部分)还是私有的。

假设是后一种情况,它会如何工作? VisualComponent 接口定义的唯一方法是Draw() 和Resize(),它们都不真正适用于滚动控件的任务(通常通过用户单击和拖动鼠标)。我已经用[3] 标记了可能的调用,但我不确定它们是否正确。

假设是前一种情况,该方法使用新的公共方法扩展了类的接口,这就是我的问题的要点。客户应该如何调用该方法?如果它不是顶级装饰器(如我们的示例中),则它无法访问 component 字段,因为它是私有的。

所以,总结一下 - 装饰器类可以添加新的 public 方法吗?如果是这样,这些应该如何调用?如果不是(在这种情况下,他们只能添加新的 private 方法),这些方法是否应该仅以适合组件接口中定义的行为的方式扩展对象的行为(在我们的例子中是VisualComponent)?例如,如果组件接口只定义了一个Draw()方法,那么这些新的私有方法是否应该只处理绘图/外观?

【问题讨论】:

    标签: design-patterns language-agnostic decorator


    【解决方案1】:

    虽然没有什么能阻止您通过装饰器添加新的公共方法,但它可能不是最好的解决方案。您已经正确地注意到,除非对象被装饰器类型的变量引用,否则客户端将无法调用该方法。

    在this answer 中,建议您在这种情况下使用继承或适配器模式。这听起来像是避免上述缺点的合理解决方案。

    【讨论】:

      猜你喜欢
      • 2017-05-25
      • 1970-01-01
      • 2013-05-07
      • 2013-02-19
      • 2012-01-28
      • 2016-06-11
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      相关资源
      最近更新 更多