I have a question about the decorator pattern
Lets say I have this code
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?")));
}
}
We have a class called thing that is wrapped by two decorators Aaa and Bbb
How can I best access the string value “CanSeeThisValue” (which is in Thing) from Aaa or Bbb
I tried to make a base class for them all, but of course while they share the same base, they don’t share the same instance of the base
Do I need to pass the value into each constructor instead?
Decorators add functionality to the public interface of the items they are wrapping. If you want your decorator to access members of
Thing, that are not part ofIThingy, then you should consider whether the decorator should wrapThinginstead ofIThingy.Or, if all
IThingyshould have aCanSeeThisValueproperty, make that property part of theIThingyinterface as well by adding (and implementing) it as a property.Which would make
Thinglook like: