-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
124 lines (102 loc) · 2.74 KB
/
Program.cs
File metadata and controls
124 lines (102 loc) · 2.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
using System;
namespace Decorator;
// Component interface
public interface ICoffee
{
string GetDescription();
double GetCost();
}
// Concrete Component
public class SimpleCoffee : ICoffee
{
public string GetDescription()
{
return "Simple Coffee";
}
public double GetCost()
{
return 2.00;
}
}
// Base Decorator
public abstract class CoffeeDecorator(ICoffee coffee) : ICoffee
{
// Using C# 14 field keyword with required modifier
protected ICoffee Coffee
{
get;
init => field = value ?? throw new ArgumentNullException(nameof(value));
} = coffee;
public virtual string GetDescription()
{
return Coffee.GetDescription();
}
public virtual double GetCost()
{
return Coffee.GetCost();
}
}
// Concrete Decorators
public class MilkDecorator : CoffeeDecorator
{
public MilkDecorator(ICoffee coffee) : base(coffee) { }
public override string GetDescription()
{
return Coffee.GetDescription() + ", Milk";
}
public override double GetCost()
{
return Coffee.GetCost() + 0.50;
}
}
public class SugarDecorator : CoffeeDecorator
{
public SugarDecorator(ICoffee coffee) : base(coffee) { }
public override string GetDescription()
{
return Coffee.GetDescription() + ", Sugar";
}
public override double GetCost()
{
return Coffee.GetCost() + 0.25;
}
}
public class WhipDecorator : CoffeeDecorator
{
public WhipDecorator(ICoffee coffee) : base(coffee) { }
public override string GetDescription()
{
return Coffee.GetDescription() + ", Whipped Cream";
}
public override double GetCost()
{
return Coffee.GetCost() + 0.75;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("=== Decorator Pattern Demo ===");
Console.WriteLine();
// Simple coffee
ICoffee coffee = new SimpleCoffee();
Console.WriteLine($"{coffee.GetDescription()} - ${coffee.GetCost()}");
// Coffee with milk
coffee = new MilkDecorator(new SimpleCoffee());
Console.WriteLine($"{coffee.GetDescription()} - ${coffee.GetCost()}");
// Coffee with milk and sugar
coffee = new SugarDecorator(new MilkDecorator(new SimpleCoffee()));
Console.WriteLine($"{coffee.GetDescription()} - ${coffee.GetCost()}");
// Coffee with everything
coffee = new WhipDecorator(
new SugarDecorator(
new MilkDecorator(new SimpleCoffee())
)
);
Console.WriteLine($"{coffee.GetDescription()} - ${coffee.GetCost()}");
Console.WriteLine();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}