Decorator pattern

Decorator design pattern allows to attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

Decorator
Decorator

Client

[TestMethod]
public void DecoratorTest()
{
    IComponent concreteComponent = new ConcreteComponent1();
    IComponent concreteDecorator1 = new ComponentDecorator1(concreteComponent);
    IComponent concreteDecorator2 = new ComponentDecorator2(concreteDecorator1);

    Assert.AreEqual(concreteDecorator1.Operation(), "ComponentDecorator1 + " + concreteComponent.Operation());
    Assert.AreEqual(concreteDecorator2.Operation(), "ComponentDecorator2 + " + ((ComponentDecorator2)concreteDecorator2).ExtendedOperation() + " + ComponentDecorator1 + " + concreteComponent.Operation());
}

The Component defines the interface for components that can have dynamically attached responsibilities.

/// <summary>
/// Declares the interface for components that can have dynamically attached responsibilities. 
/// </summary>
public interface IComponent
{
    string Operation();
}

The ConcreteComponent implements the Component’s interface to which responsibilities can be attached dynamically.

/// <summary>
/// Implements the Component's interface to which responsibilities can be attached dynamically.
/// </summary>
public class ConcreteComponent1 : IComponent
{

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

The Decorator maintains a reference to the Component’s object and defines the interface that conforms the Component’s interface

/// <summary>
/// Maintance a reference to the Component's object and define an interface that conforms the component's interface 
/// </summary>
public abstract class AbstractComponentDecorator : IComponent
{

    private IComponent _refToConcreteComponent;

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


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

The ComponentDecorator adds responsibilities to an attached component.

/// <summary>
/// Adds responsibilites to a component 
/// </summary>
public class ComponentDecorator1 : AbstractComponentDecorator
{
    public ComponentDecorator1(IComponent concreteComponent) : base(concreteComponent) { }

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s