-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTemplate Method Pattern.cs
More file actions
54 lines (48 loc) · 1.29 KB
/
Template Method Pattern.cs
File metadata and controls
54 lines (48 loc) · 1.29 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
Template Method Pattern
Definition:
Defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
Use Case:
Creating a framework for a cooking recipe where each recipe has steps, but specific details can be implemented in subclasses.
Example:
csharp
Copy code
// Abstract Class
public abstract class Recipe
{
public void Cook()
{
GatherIngredients();
Prepare();
CookMethod();
Serve();
}
protected abstract void GatherIngredients();
protected abstract void Prepare();
protected abstract void CookMethod();
private void Serve() => Console.WriteLine("Serving the dish.");
}
// Concrete Class
public class PastaRecipe : Recipe
{
protected override void GatherIngredients()
{
Console.WriteLine("Gathering pasta, sauce, and cheese.");
}
protected override void Prepare()
{
Console.WriteLine("Boiling pasta and preparing sauce.");
}
protected override void CookMethod()
{
Console.WriteLine("Cooking pasta with sauce.");
}
}
// Usage
class Program
{
static void Main()
{
var pastaRecipe = new PastaRecipe();
pastaRecipe.Cook();
}
}