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

Veröffentlicht: vor einem monat
Lesedauer ca. 36 Sekunden

decorator pattern UML diagram

interface IComponent
{
	void Operation();
}

class ConcreteComponent : IComponent
{
	public void Operation() => Console.WriteLine("ConcreteComponent");
}

class DecoratedComponentA : IComponent
{
	private IComponent _component;

	public DecoratedComponentA(IComponent component) => _component = component;

	public void Operation()
	{
		_component.Operation();
		Console.WriteLine("DecoratedComponentA");
	}
}

class DecoratedComponentB : IComponent
{
	private IComponent _component;

	public DecoratedComponentB(IComponent component) => _component = component;

	public void Operation()
	{
		_component.Operation();
		Console.WriteLine("DecoratedComponentB");
	}
}

public class Client
{
	public void Main()
	{
		IComponent component = new ConcreteComponent();
		component = new DecoratedComponentA(component);
		component = new DecoratedComponentB(component);

		component.Operation();

		/**
		 * OUTPUT:
		 *
		 * ConcreteComponent
		 * DecoratedComponentA
		 * DecoratedComponentB
		 */
	}
}
Kategorien:
Design Pattern