A Simple implementation for decorator pattern

For detailed explanation of decorator pattern, please check this link: https://alagesann.com/2013/08/16/decorator-pattern-made-easy/


public interface IPizza
 {
 int GetPrice();
 }

 public class Pizza : IPizza
 {
 public int GetPrice()
 {
 return 10;
 }
 }

 public class PizzaWithCheese : IPizza
 {
 private int CheesePrice { get; set; }
 private IPizza pizza;
 public PizzaWithCheese(IPizza pizza,int price)
 {
 this.pizza = pizza;
 CheesePrice = price;
 }
 public int GetPrice()
 {
 return pizza.GetPrice() + CheesePrice;
 }
 }

 public class PizzaWithChicken : IPizza
 {
 private int ChickenPrice { get; set; }
 private IPizza pizza;
 public PizzaWithChicken(IPizza pizza, int price)
 {
 this.pizza = pizza;
 ChickenPrice = price;
 }
 public int GetPrice()
 {
 return pizza.GetPrice() + ChickenPrice;
 }
 }

 class Program
 {
 static void Main(string[] args)
 {
 IPizza pizza = new Pizza();
 Console.WriteLine("Default pizza price=" + pizza.GetPrice());
 IPizza pizzaWithCheese = new PizzaWithCheese(pizza, 10);
 Console.WriteLine("pizza with cheese price=" + pizzaWithCheese.GetPrice());

IPizza pizzaWithChicken = new PizzaWithChicken(pizza, 20);
 Console.WriteLine("pizza with chicken price=" + pizzaWithChicken.GetPrice());

IPizza pizzaWithCheeseAndChicken = new PizzaWithChicken(pizzaWithCheese, 20);
 Console.WriteLine("pizza with cheese and chicken price=" + pizzaWithCheeseAndChicken.GetPrice());
 Console.ReadKey();
 }
 }

Sample output:


Default pizza price=10
pizza with cheese price=20
pizza with chicken price=30
pizza with cheese and chicken price=40

Advertisements

One thought on “A Simple implementation for decorator pattern

  1. Pingback: Decorator pattern made easy | Alagesan Palani

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s