gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:22:46 24 4
gpt4 key购买 nike

我有一个关于装饰器模式的问题

假设我有这段代码

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

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

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

最佳答案

装饰器向它们包装的项目的公共(public)接口(interface)添加功能。如果你想让你的装饰器访问 Thing 的成员,而不是 IThingy 的一部分,那么你应该考虑装饰器是否应该包装 Thing IThingy 的。

或者,如果所有 IThingy 都应该有一个 CanSeeThisValue 属性,则通过添加(和实现)使该属性成为 IThingy 接口(interface)的一部分) 它作为一个属性。

interface IThingy 
{
string CanSeeThisValue { get; }

void Execute();
}

这将使 Thing 看起来像:

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

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

...

}

关于c# - 装饰器模式 - 从装饰器访问包装对象中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10400619/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com