Decorator Design Pattern

Introduction:
Sometimes you want to add more responsibility to an object dynamically. Decorate Design Pattern provide us a flexible alternative to creating subclasses to extend this functionality. So you will not have to extend functionality by creating a child (Sub class) class.
Example:

DecoratorDesignPattern

class Program
{
static void Main()
{
Book b = new Book();
b.BookName = “Book Name”;
b.AutherName = “Auther Name”;
b.NumCopies = 10;
b.Display();
Movie v = new Movie();
v.VideoName = “Some Video name”;
v.VideoDirector = ” a Director”;
v.PlayTime = “1 hour”;
v.NumCopies = 10;
v.Display();
Console.WriteLine(“———————-“);
Console.WriteLine(“Borrow the book”);
BorrowLibraryItem borrow = new BorrowLibraryItem(b);
borrow.BorrowItem(“Yasser Jaber”);
borrow.BorrowItem(“Salah Jaber”);
borrow.Display();
Console.ReadKey();
}
}
abstract class LibraryItem
{
public int NumCopies{get;set;}
public abstract void Display();
}
class Book:LibraryItem
{
public string BookName { get; set; }
public string AutherName { get; set; }
public override void Display()
{
Console.WriteLine();
Console.WriteLine(“–> Book : “);
Console.WriteLine(” Author: {0}”, this.AutherName);
Console.WriteLine(” Book Name: {0}”, this.BookName);
Console.WriteLine(” Number of Copies: {0}”, base.NumCopies);
}
}
class Movie: LibraryItem
{
public string VideoDirector { get; set; }
public string VideoName { get; set; }
public string PlayTime { get; set; }
public override void Display()
{
Console.WriteLine( );
Console.WriteLine(“–>Movie : “);
Console.WriteLine(” Director: {0}”, VideoDirector);
Console.WriteLine(” Name: {0}”, VideoName);
Console.WriteLine(” Number of Copies: {0}”, NumCopies);
Console.WriteLine(” Playtime: {0}”, PlayTime);
}
}
class BorrowLibraryItem
{
protected List<string> borrowers = new List<string>();
protected LibraryItem item;
public BorrowLibraryItem(LibraryItem item)
{
this.item = item;
}
public void BorrowItem(string borrowerName)
{
borrowers.Add(borrowerName);
item.NumCopies–;
}
public void ReturnItem(string borrowerName)
{
borrowers.Remove(borrowerName);
item.NumCopies++;
}
public void Display()
{
item.Display();
Console.WriteLine();
Console.WriteLine(“Borrowers:”);
for (int i = 1; i <= borrowers.Count; i++)
{
Console.WriteLine(i.ToString() + “. ” + borrowers[i – 1]);
}
}
}

 

Download Code