-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathProgram.cs
55 lines (45 loc) · 1.35 KB
/
Program.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
namespace DesignPatterns.Flyweight;
enum CalculateType
{
Adder, Multiplier
}
interface ICalculator
{
void Calculate(int val1, int val2);
}
class CalculateMultiplier : ICalculator
{
public void Calculate(int val1, int val2) =>Console.WriteLine($"{val1} * {val2} = {val1 * val2}");
}
class CalculateAdder : ICalculator
{
public void Calculate(int val1, int val2)=> Console.WriteLine($"{val1} + {val2} = {val1 + val2}");
}
class CalculatorFactory
{
private readonly Dictionary<CalculateType, ICalculator> _memoryObject = new();
public ICalculator GetCalculator(CalculateType type)
{
if (!_memoryObject.ContainsKey(type))
{
_memoryObject[type] = type switch
{
CalculateType.Adder => new CalculateAdder(),
CalculateType.Multiplier => new CalculateMultiplier(),
_ => throw new ArgumentException("Invalid type")
};
}
return _memoryObject[type];
}
}
class App
{
public static void Main(string[] args)
{
var calculatorFactory = new CalculatorFactory();
ICalculator adder = calculatorFactory.GetCalculator(CalculateType.Adder);
adder.Calculate(1, 2);
ICalculator multiplier = calculatorFactory.GetCalculator(CalculateType.Multiplier);
multiplier.Calculate(4, 2);
}
}