Code in C#:
namespace
Decorator_DesignPattern
{
using System;
abstract class Component
{
public abstract void Draw();
}
class ConcreteComponent : Component
{
private string strName;
public ConcreteComponent(string s)
{
strName = s;
}
public override void Draw()
{
Console.WriteLine("ConcreteComponent - {0}", strName);
}
}
abstract class Decorator : Component
{
protected Component ActualComponent;
public void SetComponent(Component c)
{
ActualComponent = c;
}
public override void Draw()
{
if (ActualComponent != null)
ActualComponent.Draw();
}
}
class ConcreteDecorator : Decorator
{
private string strDecoratorName;
public ConcreteDecorator (string str)
{
// how decoration occurs is localized inside this decorator
// For this demo, we simply print a decorator name
strDecoratorName = str;
}
public override void Draw()
{
CustomDecoration();
base.Draw();
}
void CustomDecoration()
{
Console.WriteLine("In ConcreteDecorator: decoration goes here");
Console.WriteLine("{0}", strDecoratorName);
}
}
///<summary>
/// Summary description for Client.
///</summary>
public class Client
{
Component Setup()
{
ConcreteComponent c = new ConcreteComponent("This is the real component");
ConcreteDecorator d = new ConcreteDecorator("This is a decorator for the component");
d.SetComponent(c);
return d;
}
public static int Main(string[] args)
{
Client client = new Client();
Component c = client.Setup();
// The code below will work equally well with the real component,
// or a decorator for the component
c.Draw();
return 0;
}
}
}
Code in SOME:
AComponent
a_Draw()
CConcreteComponent :AComponent
(string _strName)
o_Draw()
ADecorator : AComponent, ->AComponent[m_actualComponent]
SetComponent(AComponent)
o_Draw()
CConcreteDecorator : ADecorator
(string _strDecoratorName)
o_Draw()
CustomDecoration()
CClient
AComponent Setup()
main
CClient.main
{
CClient client.();
AComponent c = client.Setup()
{
CConcreteComponent c.("This is the real component");
CConcreteDecorator d.("This is a decorator for the component");
d.SetComponent( m_actualComponent = c ); //quick assignment for set method
d; //return d;
};
c.Draw<CConcreteDecorator>()
{
CustomDecoration();
Draw<ADecorator>() //invoke base method
{
m_actualComponent.Draw<CConcreteComponent>()
{
<% Console.WriteLine("ConcreteComponent - {0}", _strName); %>
};
};
};
}