Decorator Pattern 의 장단점
장점
- 단일 책임 원칙
- 기존 Class 의 코드를 수정하지 않고 Decorator Class를 추가
단점
- 객체(Decorator Class) 수 증가
- 여러 객체(Decorator Class)의 순서 의존성, 조합 과정에서의 복잡성 문제
구성요소
Component : Interface 나 Abstact Class 로 구현하고, 대상임
Concretecomponent : component의 추상적인 기능을 구현 시킨 class
Decorator : Interface 나 Abstact Class 로 구현하고, Component 의 Decorator 임
ConcreteDecorator : Decorator의 추상적인 기 을 구현 시킨 class
샘플코드
coffee 와 관련해서 구현 해 보았다.
sugar, milk 두 개의 Decorator 를 구현 해 보았다

namespace practice_csharp
{
public class Program
{
static void Main(string[] args)
{
ICoffee coffee = new BasicCoffee();
coffee = new MilkCoffee(coffee);
coffee = new SugarCoffee(coffee);
Console.WriteLine($"Description: {coffee.GetDescription()}, Cost: {coffee.GetCost()}");
}
}
}
public interface ICoffee
{
string GetDescription();
double GetCost();
}
public class BasicCoffee : ICoffee
{
public string GetDescription()
{
return "Basic Coffee";
}
public double GetCost()
{
return 5.0f;
}
}
public abstract class CoffeeDecorator : ICoffee
{
protected ICoffee decoratedCoffee;
public CoffeeDecorator(ICoffee coffee)
{
this.decoratedCoffee = coffee;
}
public virtual string GetDescription()
{
return decoratedCoffee.GetDescription();
}
public virtual double GetCost()
{
return decoratedCoffee.GetCost();
}
}
public class SugarCoffee : CoffeeDecorator
{
public SugarCoffee(ICoffee coffee) : base(coffee)
{
}
public override string GetDescription()
{
return base.GetDescription() + ", Sugar ";
}
public override double GetCost()
{
return base.GetCost() + 1;
}
}
public class MilkCoffee : CoffeeDecorator
{
public MilkCoffee(ICoffee coffee) : base(coffee)
{
}
public override string GetDescription()
{
return base.GetDescription() + ", Milk ";
}
public override double GetCost()
{
return base.GetCost() + 2;
}
}