September 23, 2003

Structural Pattern – Decorator

“Attach additional responsibilities to an object dynamically.”

• Related to the Composite pattern

• Most commonly used when drawing objects.

Example:

Form.Draw(rect) {

// … draw form …

foreach(Element e in elements)

e.Draw(rect)

}

Example-
namespace Patterns {
interface IComponent {
string Operation();
}

class Original : IComponent {
public string Operation() {
return "I'm original but ";
}
}

class Decorate : IComponent {
IComponent _compo;
public Decorate(IComponent c) {
_compo = c;
}

public string Operation() {
string s = _compo.Operation();
s += "I'm decorated too.";
return s;
}
}

public class DecoExample {
public void test() {
IComponent c = new Original();
Decorate d = new Decorate(c);
Console.WriteLine(d.Operation());
}
}
}

Links: