fork download
  1. using System;
  2. public class Cake
  3. {
  4. public virtual decimal Cost { get;set; }
  5. public virtual string Name {get;set;}
  6. public virtual int Calories{get;set;}
  7.  
  8. public virtual void Bake()
  9. {
  10. AddLiquidIngredients();
  11. AddSolidIngredients();
  12. MixCake();
  13. }
  14.  
  15. private void MixCake()
  16. {
  17. //You could be selling not mixed cake?
  18. Cost += 2;
  19. }
  20.  
  21. private void AddLiquidIngredients()
  22. {
  23. //Imagine the cost of each ingredients + calories etc.
  24. Cost += 1;
  25. Calories += 100;
  26. }
  27.  
  28. private void AddSolidIngredients()
  29. {
  30. //Imagine the cost of each ingredients + calories etc.
  31. Cost += 2;
  32. Calories += 150;
  33. }
  34. }
  35.  
  36. public class FrostedCake : Cake
  37. {
  38. private Cake cake;
  39.  
  40. public override decimal Cost
  41. {
  42. get{return cake.Cost;}
  43. set{cake.Cost = value;}
  44. }
  45.  
  46. public override int Calories
  47. {
  48. get{return cake.Calories;}
  49. set{cake.Calories = value;}
  50. }
  51.  
  52. public override string Name
  53. {
  54. get{return cake.Name;}
  55. set{cake.Name = value;}
  56. }
  57.  
  58. public FrostedCake(Cake cake)
  59. {
  60. this.cake = cake;
  61. }
  62.  
  63. public override void Bake()
  64. {
  65. cake.Bake();
  66. Frost();
  67. }
  68.  
  69. private void Frost()
  70. {
  71. Name += " frosted";
  72. Calories += 200;
  73. Cost += 5;
  74. }
  75. }
  76.  
  77.  
  78. public class Test
  79. {
  80. public static void Main()
  81. {
  82. Cake cake = new Cake();
  83. cake.Name = "Super cake";
  84. cake.Cost = 10;
  85.  
  86. //I want a cake to be frosted
  87. cake = new FrostedCake(cake);
  88.  
  89. /*
  90. The frosted cake is an "add-on" to the cake itself. A frosted cake is nothing without a cake.
  91. But the cake can exist by itself.
  92. By using the decorator pattern you can, at runtime, add functionality to your existing instance of a class.
  93. */
  94.  
  95. cake.Bake();
  96. Console.WriteLine(cake.Name);
  97. }
  98. }
Success #stdin #stdout 0.04s 23944KB
stdin
Standard input is empty
stdout
Super cake frosted