【发布时间】: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