Skip to content

Instantly share code, notes, and snippets.

@AlexArchive
Created October 25, 2013 00:09
Show Gist options
  • Select an option

  • Save AlexArchive/7147351 to your computer and use it in GitHub Desktop.

Select an option

Save AlexArchive/7147351 to your computer and use it in GitHub Desktop.
class DecoratorPattern
{
interface IComponent
{
string Operation();
}
class Component : IComponent
{
public string Operation()
{
return "I am walking ";
}
}
class DecoratorA : IComponent
{
private IComponent component;
public DecoratorA(IComponent component)
{
this.component = component;
}
public string Operation()
{
string s = component.Operation();
s += "and listening to Classic FM ";
return s;
}
}
class DecoratorB : IComponent
{
private IComponent component;
public string AddedState
{
get
{
return "past the Coffee Shop ";
}
}
public DecoratorB(IComponent component)
{
this.component = component;
}
public string Operation()
{
string s = component.Operation();
s += "to school ";
return s;
}
public string AddedBehaviour()
{
return "and I bought a cappuccino ";
}
}
static class Client
{
static void Display(string s, IComponent component)
{
Console.WriteLine(s + component.Operation());
}
static void Main(string[] args)
{
Console.WriteLine("Decorator Pattern\n");
IComponent component = new Component();
Display("1. Basic Component: " , component);
DecoratorA decoratorA = new DecoratorA(component);
Display("2. A-decorated: ", decoratorA);
DecoratorB decoratorB = new DecoratorB(component);
Display("3. B-decorated: ", decoratorB);
DecoratorB decoratorBA = new DecoratorB(new DecoratorA(component));
Display("4. B-A-decorated: ", decoratorBA);
DecoratorA decoratorAB = new DecoratorA(new DecoratorB(component));
Display("4. A-B-decorated: ", decoratorAB);
Console.WriteLine("\t\t\t" + decoratorB.AddedState + decoratorB.AddedBehaviour());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment