Structural.Decorator design pattrn

Allows to add responsibilities dynamically without subclassing


/*
* Attaches additional responisbilities for an object dynamically.
* Allows to add additional behavior without subclassing
*/
namespace Structural.Decorator
{
///

/// Declares an interface for components.
///

public interface IComponent
{
string Operation();
}

///

/// Implements component interface
///

public class ConcreteComponent1 : IComponent
{

public string Operation()
{
return "ConcreteComponent1";
}
}

///

/// Implements component interface
///

public class ConcreteComponent2 : IComponent
{

public string Operation()
{
return "ConcreteComponent2";
}
}

///

/// Maintains a reference to a component. Implements a basic operations of a component
///

public abstract class AbstractComponentDecorator : IComponent
{

private IComponent _refToConcreteComponent;

public AbstractComponentDecorator(IComponent concreteComponent)
{
_refToConcreteComponent = concreteComponent;
}

public virtual string Operation()
{
return _refToConcreteComponent.Operation();
}
}

///

/// Extends functionality of a component, provides a reference to a component
///

public class ComponentDecorator1 : AbstractComponentDecorator
{
public ComponentDecorator1(IComponent concreteComponent) : base(concreteComponent) { }

public override string Operation()
{
return "ComponentDecorator1 + " + base.Operation();
}
}

///

/// Extends functionality of a component, provides a reference to a component
///

public class ComponentDecorator2 : AbstractComponentDecorator
{
public ComponentDecorator2(IComponent concreteComponent) : base(concreteComponent) { }

public override string Operation()
{
return "ComponentDecorator2 + " + ExtendedOperation() + " + " + base.Operation();
}

public string ExtendedOperation()
{
return "ExtendedOperation";
}
}

}