装饰器模式 - 从装饰器访问包装对象中的值

时间:2012-05-01 16:12:51

标签: c# design-patterns decorator

我对装饰器模式有疑问

让我说我有这个代码

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中)

我试图为他们创建一个基类,但当然,当他们共享相同的基础时,他们不共享相同的基础实例

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

1 个答案:

答案 0 :(得分:2)

装饰器将功能添加到它们包装的项目的公共接口。如果您希望装饰者访问不属于Thing的{​​{1}}成员,那么您应该考虑装饰者是否应该包裹IThingy而不是Thing

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

IThingy

这会使interface IThingy { string CanSeeThisValue { get; } void Execute(); } 看起来像:

Thing
相关问题