المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : c# decorator pattern: how to pass the data from base to the last child object ?



C# Programming
08-02-2010, 08:11 AM
Hi, i started from some example,
http://www.dofactory.com/Patterns/PatternDecorator.aspx#_self1[^ (http://www.dofactory.com/Patterns/PatternDecorator.aspx#_self1)]

then added a var in the Component class.
In the end, seems d2 cannot access var,
i mean d2.component.var is not there,
instead it's sth. like d2.base.base.component.var.

This looks different from c++, anyone knows how to get d2.component.var directly ?




using System;

namespace DoFactory.GangOfFour.Decorator.Structural
{
class MainApp
{
static void Main()
{
ConcreteComponent c = new ConcreteComponent(5);
ConcreteDecoratorA d1 = new ConcreteDecoratorA();
ConcreteDecoratorB d2 = new ConcreteDecoratorB();

d1.SetComponent(c);
d2.SetComponent(d1);

d2.Operation();
}
}

abstract class Component
{
public int var; // i added this
public abstract void Operation();
public Component(int n){var = n;} // i added this
}

class ConcreteComponent : Component
{
public ConcreteComponent(int n):base(n){}
public override void Operation()
{
Console.WriteLine("ConcreteComponent.Operation() {0}", var);
}
}

abstract class Decorator : Component
{
protected Component component;

public void SetComponent(Component component)
{
this.component = component;
}

public override void Operation()
{
if (component != null)
{
component.Operation();
}
}
}

class ConcreteDecoratorA : Decorator
{
public override void Operation()
{
base.Operation();
Console.WriteLine("ConcreteDecoratorA.Operation()");
}
}

class ConcreteDecoratorB : Decorator
{
public override void Operation()
{
base.Operation();
AddedBehavior();
Console.WriteLine("ConcreteDecoratorB.Operation()");
}

void AddedBehavior()
{
}
}
}
wow