forked from ahotko/c-sharp-code-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFactoryMethodPattern.cs
72 lines (64 loc) · 1.89 KB
/
FactoryMethodPattern.cs
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
using System;
using System.Collections.Generic;
namespace CodeSamples.Patterns.Creational
{
#region Factory Method Pattern Classes and Interfaces
abstract class VeganStuff { }
class Bread : VeganStuff { }
class Cheese : VeganStuff { }
class Tomato : VeganStuff { }
class Lettuce : VeganStuff { }
class Mayonnaise : VeganStuff { }
abstract class Sandwich
{
public Sandwich()
{
MakeSandwich();
}
//Factory Method
public abstract void MakeSandwich();
public List<VeganStuff> Ingredients { get; } = new List<VeganStuff>();
public void ListIngredients()
{
foreach(var ingredient in Ingredients)
{
Console.WriteLine($" ingredient = {ingredient.GetType().Name}");
}
}
}
class VeggieSandwich : Sandwich
{
public override void MakeSandwich()
{
Ingredients.Add(new Bread());
Ingredients.Add(new Lettuce());
Ingredients.Add(new Tomato());
Ingredients.Add(new Cheese());
Ingredients.Add(new Mayonnaise());
Ingredients.Add(new Bread());
}
}
class TomatoSandwich : Sandwich
{
public override void MakeSandwich()
{
Ingredients.Add(new Bread());
Ingredients.Add(new Tomato());
Ingredients.Add(new Bread());
}
}
#endregion
public class FactoryMethodPatternSample : SampleExecute
{
public override void Execute()
{
Section("Factory Method Pattern");
Section("Veggie Sandwich");
var veggieSandwich = new VeggieSandwich();
veggieSandwich.ListIngredients();
Section("Tomato Sandwich");
var tomatoSandwich = new TomatoSandwich();
tomatoSandwich.ListIngredients();
}
}
}