Programming - Decorator Structural Design Pattern


Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.


The classes and/or objects participating in this pattern are:


  • Componentand
    and and
    • defines the interface for objects that can have responsibilities added to them dynamically.
  • ConcreteComponentand
    and and
    • defines an object to which additional responsibilities can be attached.
  • Decoratorand
    and
    • maintains a reference to a Component object and defines an interface that conforms to Component's interface.
  • ConcreteDecoratorand
    and
    • adds responsibilities to the component.
// Decorator pattern -- Structural example

using
System;

namespace
DoFactory.GangOfFour.Decorator.Structural
{

// MainApp test application

class MainApp
{
static void Main()
{
// Create ConcreteComponent and two Decorators
ConcreteComponent c = new ConcreteComponent();
ConcreteDecoratorA d1 = new ConcreteDecoratorA();
ConcreteDecoratorB d2 = new ConcreteDecoratorB();

// Link decorators
d1.SetComponent(c);
d2.SetComponent(d1);

d2.Operation();

// Wait for user
Console.Read();
}
}

// "Component"

abstract class Component
{
public abstract void Operation();
}

// "ConcreteComponent"

class ConcreteComponent : Component
{
public override void Operation()
{
Console.WriteLine("ConcreteComponent.Operation()");
}
}

// "Decorator"

abstract class Decorator : Component
{
protected Component component;

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

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

// "ConcreteDecoratorA"

class ConcreteDecoratorA : Decorator
{
private string addedState;

public override void Operation()
{
base.Operation();
addedState = "New State";
Console.WriteLine("ConcreteDecoratorA.Operation()");
}
}

// "ConcreteDecoratorB"

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

void AddedBehavior()
{
}
}
}


Output expected:


ConcreteComponent.Operation()
ConcreteDecoratorA.Operation()
ConcreteDecoratorB.Operation()


Home | Privacy Policy | Site Map | Links | Company | Contact Us | Arena           

We provide cutting edge software development, consultancy and web design services            

There are currently 646 user(s) with 40656 hits.