【问题标题】:Decorator pattern - access value in wrapped object from decorator装饰器模式 - 从装饰器访问包装对象中的值
【发布时间】:2012-05-01 16:12:50
【问题描述】:

我对装饰器模式有疑问

假设我有这个代码

interface IThingy 
{
    void Execute(); 
}

internal class Thing : IThingy
{
    public readonly string CanSeeThisValue;

    public Thing(string canSeeThisValue)
    {
        CanSeeThisValue = canSeeThisValue;
    }

    public void Execute()
    {
        throw new System.NotImplementedException();
    } 
}

class Aaa : IThingy 
{
    private readonly IThingy thingy;

    public Aaa(IThingy thingy)
    {
        this.thingy = thingy;
    }

    public void Execute()
    {
        throw new System.NotImplementedException();
    } 
}


class Bbb : IThingy {
    private readonly IThingy thingy;

    public Bbb(IThingy thingy)
    {
        this.thingy = thingy;
    }

    public void Execute()
    {
        throw new System.NotImplementedException();
    } 
}

class Runit {
    void Main()
    {
        Aaa a = new Aaa(new Bbb(new Thing("Can this be accessed in decorators?")));
    } 
}

我们有一个名为 thing 的类,它由两个装饰器 Aaa 和 Bbb 包装

如何最好地从 Aaa 或 Bbb 访问字符串值“CanSeeThisValue”(在 Thing 中)

我尝试为它们都创建一个基类,但当然,虽然它们共享相同的基类,但它们并不共享相同的基类实例

我是否需要将值传递给每个构造函数?

【问题讨论】:

  • 装饰器使用他们所包装的任何东西的公共接口来增强功能,通常他们应该知道除此之外的任何东西。
  • 你能在基类中将该字段设为静态吗?或者向 IThingy 添加新属性?这样就可以在循环中使用装饰类来检索该属性的值。

标签: c# design-patterns decorator


【解决方案1】:

装饰器将功能添加到它们正在包装的项目的公共接口中。如果你想让你的装饰器访问不属于IThingyThing的成员,那么你应该考虑装饰器是否应该包装Thing而不是IThingy

或者,如果所有IThingy 都应该有一个CanSeeThisValue 属性,则将该属性作为IThingy 接口的一部分添加(并实现)为属性。

interface IThingy 
{
    string CanSeeThisValue { get; }

    void Execute(); 
}

这会使Thing 看起来像:

internal class Thing : IThingy
{
    public string CanSeeThisValue { get; private set; }

    public Thing(string canSeeThisValue)
    {
        CanSeeThisValue = canSeeThisValue;
    }

    ...

} 

【讨论】:

    猜你喜欢
    • 2021-06-05
    • 1970-01-01
    • 2011-06-25
    • 1970-01-01
    • 2012-08-27
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多