Chr*_*sCa 5 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?")));
}
}
Run Code Online (Sandbox Code Playgroud)
我们有一个名为 thing 的类,它由两个装饰器 Aaa 和 Bbb 包裹
如何最好地从 Aaa 或 Bbb 访问字符串值“CanSeeThisValue”(在 Thing 中)
我试图为他们所有人创建一个基类,但是当然,虽然它们共享相同的基类,但它们不共享基类的相同实例
我是否需要将值传递给每个构造函数?
装饰器向它们所包装的项目的公共接口添加功能。如果您希望装饰器访问Thing不属于 的成员IThingy,那么您应该考虑装饰器是否应该换行Thing而不是IThingy。
或者,如果所有内容都IThingy应该有一个CanSeeThisValue属性,IThingy则通过将其添加(和实现)为属性来使该属性成为接口的一部分。
interface IThingy
{
string CanSeeThisValue { get; }
void Execute();
}
Run Code Online (Sandbox Code Playgroud)
这会让Thing看起来像:
internal class Thing : IThingy
{
public string CanSeeThisValue { get; private set; }
public Thing(string canSeeThisValue)
{
CanSeeThisValue = canSeeThisValue;
}
...
}
Run Code Online (Sandbox Code Playgroud)