Decorator Design Pattern Using C#

Decorator Design Pattern using C#

In this pattern, we would learn how an object can be decorated with additional functionality dynamically without subclassing. It is also known as Wrapper. The decorator pattern follows the Single Responsibility Principle, as it allows functionality to be distributed among classes with unique responsibility. Let’s take a deep dive into the pattern.

As per GoF, the decorator pattern is defined as shown below:

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

What we learn from the definition as stated above is that Decorator pattern is often used when we want to add behavior to an individual object not to an entire class at the run time, without affecting the behavior of other objects from the same class.

Example:

Let’s say we have a shop that sells phones of all type, iPhone, Android, Windows Phone, etc. Phones either fall in SmartPhone category or in normal Phone category. Every phone has its price, brand name and description along with it. Now shopkeeper wants to offer students discount on the phone prices. He has also got festival discounts on the phone.

Normal Approach

A bad design would lead you to change the behavior of the Phone class. But that is very inflexible as every time shopkeeper wants to offer a new discount based on festive season, he needs to change the Phone class. That means client can’t control how and when to decorate the object.

Design Pattern Approach

A more flexible approach is to enclose the object in another object that adds extra behavior to the object. Mapping to our example, if we have StudentOffer and ChristmasOffer classes, these classes enclose the main components i.e. Phone. The class which decorates the main object is called Decorator. Decorator maintains transparency to the decorated object’s client.

Base Design

Participants in the pattern are: For the sake of understanding, I have mapped my example to the participants in decorators’ pattern.

Class diagram

BaseComponent (IMobile)

Defines the interface for objects that can have responsibilities added to them dynamically. In our case, it is IMobile.

  1. public enum Brand  
  2. {  
  3.     Samsung,  
  4.     Nokia,  
  5.     Apple,  
  6.     Xperia  
  7. }  
  8.   
  9. public enum MobileType  
  10. {  
  11.     SmartPhone,  
  12.     Normal  
  13. }  
  14.   
  15. public abstract class IMobile  
  16. {  
  17.     public abstract Brand Brand { get;  }  
  18.     public abstract double Price { get;  }  
  19.     public abstract MobileType MType { get;  }  
  20. }  
ConcreteComponent (Apple, Samsung, Nokia)

Defines an object to which additional responsibilities can be attached. Apple, Samsung are extensions of base class without any Offers.

Android
  1. public class Android : IMobile  
  2. {  
  3.     private Brand brand;  
  4.     private double _price;  
  5.     private MobileType _mtype;  
  6.   
  7.     public Android(Brand brand, double price, MobileType mtype)  
  8.     {  
  9.         this.brand = brand;  
  10.         _price = price;  
  11.         _mtype = mtype;  
  12.     }  
  13.   
  14.     public override Brand Brand  
  15.     {  
  16.         get { return brand; }  
  17.     }  
  18.   
  19.   
  20.     public override double Price  
  21.     {  
  22.         get { return _price; }  
  23.          
  24.     }  
  25.   
  26.     public override MobileType MType  
  27.     {  
  28.         get { return _mtype; }  
  29.         
  30.     }  
  31.     public override string ToString()  
  32.     {  
  33.   
  34.         StringBuilder itemDesc = new StringBuilder();  
  35.         itemDesc.Append(Enum.GetName(typeof(Brand), brand));  
  36.         itemDesc.Append(" ");  
  37.         itemDesc.Append("||");  
  38.         itemDesc.Append(" ");  
  39.         itemDesc.Append(Price);  
  40.         itemDesc.Append(" ");  
  41.         itemDesc.Append("||");  
  42.         itemDesc.Append(" ");  
  43.         itemDesc.Append(Enum.GetName(typeof(MobileType), MType));  
  44.         return itemDesc.ToString();  
  45.     }  
  46. }  
iPhone.cs
  1. public class IPhone : IMobile  
  2. {  
  3.     private Brand brand;  
  4.     private double _price;  
  5.     private MobileType _mtype;  
  6.   
  7.     public IPhone(Brand brand, double price, MobileType mtype)  
  8.     {  
  9.         this.brand = brand;  
  10.         _price = price;  
  11.         _mtype = mtype;  
  12.     }  
  13.   
  14.     public override Brand Brand  
  15.     {  
  16.         get { return brand; }  
  17.         
  18.     }  
  19.   
  20.     public override double Price  
  21.     {  
  22.         get { return _price; }  
  23.          
  24.     }  
  25.   
  26.     public override MobileType MType  
  27.     {  
  28.         get { return _mtype; }  
  29.           
  30.     }  
  31.   
  32.     public override string ToString()  
  33.     {  
  34.   
  35.         StringBuilder itemDesc= new StringBuilder();  
  36.         itemDesc.Append(Enum.GetName(typeof(Brand),brand));  
  37.         itemDesc.Append(" ");  
  38.         itemDesc.Append("||");  
  39.         itemDesc.Append(" ");  
  40.         itemDesc.Append(Price);  
  41.         itemDesc.Append(" ");  
  42.         itemDesc.Append("||");  
  43.         itemDesc.Append(" ");  
  44.         itemDesc.Append(Enum.GetName(typeof(MobileType),MType));  
  45.         return itemDesc.ToString();  
  46.     }  
  47. }  
Decorator(Offers)

Maintains a reference to component object and defines an interface that conforms to component’s interface. Offer is a abstract decorator class - note that it encapsulates IMobile.
  1. public abstract class Offer  
  2. {  
  3.     private readonly IMobile _mobile;  
  4.   
  5.     protected Offer(IMobile mobile)  
  6.     {  
  7.         this._mobile = mobile;  
  8.     }  
  9.   
  10.     public Brand Brand  
  11.     {  
  12.         get { return _mobile.Brand; }  
  13.     }  
  14.   
  15.     public double Price  
  16.     {  
  17.         get { return _mobile.Price; }  
  18.     }  
  19.   
  20.     public MobileType MType  
  21.     {  
  22.         get { return _mobile.MType; }  
  23.     }  
  24. }  
ConcreteDecorators (Christmas Offer, Student Offer): Adds responsibilities to the component e.g. the first concrete decorator which adds ChristmasOffer functionality.
  1. public sealed class ChristmasOffer:Offer  
  2. {  
  3.     public int DiscountPercentage { getset; }  
  4.   
  5.     public ChristmasOffer(IMobile mobile) : base(mobile){  
  6.         
  7.     }  
  8.   
  9.     public double CalculatedPrice  
  10.     {  
  11.         get  
  12.         {  
  13.             double price = base.Price;  
  14.             int percentage = 100 - DiscountPercentage;  
  15.             return Math.Round((price * percentage) / 100, 2);  
  16.         }  
  17.     }  
  18.   
  19. }  
Client
  1. private static void Main(string[] args)  
  2. {  
  3.     int phoneType;  
  4.   
  5.     OfferIteratorImp offerCollection = new OfferIteratorImp(GetMeCollection.GetMeOfferList());  
  6.   
  7.     Console.WriteLine("------------- Prepare Quotation for the mobile -------------");  
  8.   
  9.     Console.WriteLine("Select the Mobile type");  
  10.   
  11.     int i = 1;  
  12.     foreach (var mtype in Enum.GetNames(typeof (MobileType)))  
  13.     {  
  14.         Console.WriteLine(i + " : " + mtype);  
  15.         i++;  
  16.     }  
  17.   
  18.     string userInput = Console.ReadLine();  
  19.   
  20.     int.TryParse(userInput, out phoneType);  
  21.       
  22.   
  23.     var mType = phoneType == 1 ? MobileType.SmartPhone : MobileType.Normal;  
  24.   
  25.     Console.WriteLine("Choose the brand out of shown ones?");  
  26.   
  27.     Console.WriteLine("\n");  
  28.     Console.WriteLine("Brand || Price || Type ");  
  29.     Console.WriteLine("----------------------------");  
  30.   
  31.       
  32.     foreach (var mobile in  GetMeCollection.GetMeListOfPhones())  
  33.     {  
  34.         if (mobile.MType == mType)  
  35.         {  
  36.             Console.WriteLine(mobile);  
  37.         }  
  38.     }  
  39.   
  40.       
  41.     Console.WriteLine("\n");  
  42.     Console.WriteLine("\nAre you a student?");  
  43.       
  44.     int custType;  
  45.   
  46.     int.TryParse(Console.ReadLine(), out custType);  
  47.     bool isStudent = custType == 1 ? true : false;  
  48.   
  49.     if (isStudent)  
  50.     {  
  51.         Console.WriteLine("\n");  
  52.         Console.WriteLine("Student Prices");  
  53.         Console.WriteLine("\n");  
  54.         foreach (var listOffer in offerCollection)  
  55.         {  
  56.             if (listOffer.GetType() != typeof (StudentOffer)) continue;  
  57.             Console.WriteLine(listOffer);  
  58.             Console.WriteLine("\n");  
  59.         }  
  60.     }  
  61.   
  62.     Console.ReadKey();  
  63. }  
As you can see, the Base Component (IMobile) defines the interface for objects that can be assigned new responsibilities dynamically, and the ConcreteComponent (IPhone) is simply an implementation of this interface. The Decorator (Offer) has a reference (composition) to a Component, and also conforms to the Component interface (IMobile). This is an important thing to remember, as the Decorator is essentially wrapping the Component. The ConcreteDecorator (ChristmasOffer and StudentOffer) adds extra responsibilities to the original Component.


Similar Articles