-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
79 lines (66 loc) · 1.76 KB
/
Program.cs
File metadata and controls
79 lines (66 loc) · 1.76 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
using System;
using System.Collections.Generic;
namespace Flyweight;
public class TreeType(string name, ConsoleColor color)
{
public string Name { get; } = name;
public ConsoleColor Color { get; } = color;
public void Draw(int x, int y)
{
var previous = Console.ForegroundColor;
Console.ForegroundColor = Color;
Console.WriteLine($"Tree {Name} at ({x},{y})");
Console.ForegroundColor = previous;
}
}
public class TreeFactory
{
private readonly Dictionary<string, TreeType> cache = [];
public TreeType GetTreeType(string name, ConsoleColor color)
{
var key = $"{name}-{color}";
if (!cache.TryGetValue(key, out var type))
{
type = new TreeType(name, color);
cache[key] = type;
}
return type;
}
}
public class Forest
{
private readonly List<(int x, int y, TreeType type)> trees = [];
private readonly TreeFactory factory = new();
public void PlantTree(int x, int y, string name, ConsoleColor color)
{
var type = factory.GetTreeType(name, color);
trees.Add((x, y, type));
}
public void Draw()
{
Console.WriteLine($"Drawing {trees.Count} trees while sharing flyweights");
foreach (var (x, y, type) in trees)
{
type.Draw(x, y);
}
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("=== Flyweight Pattern Demo ===");
Console.WriteLine();
var forest = new Forest();
var random = new Random(42);
for (var i = 0; i < 5; i++)
{
forest.PlantTree(random.Next(0, 50), random.Next(0, 50), "Oak", ConsoleColor.Green);
forest.PlantTree(random.Next(0, 50), random.Next(0, 50), "Birch", ConsoleColor.Yellow);
}
forest.Draw();
Console.WriteLine();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}