-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlyweight.cs
More file actions
59 lines (47 loc) · 1.56 KB
/
Flyweight.cs
File metadata and controls
59 lines (47 loc) · 1.56 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
// Usage
void Main()
{
var counsel = new JediCounsel();
counsel.WelcomeIn("Plo Koon", "blue");
counsel.WelcomeIn("Mace Windu", "purple");
counsel.WelcomeIn("Shaak Ti", "blue");
counsel.WelcomeIn("Yoda", "green");
counsel.WelcomeIn("Ki-Adi-Mundi", "purple");
counsel.WelcomeIn("Saesee Tiin", "green");
}
public class JediCounsel
{
public List<Jedi> Council = new List<Jedi>();
public void WelcomeIn(string name, string lightsaberColor)
{
var lightsaberType = LightsaberFactory.GetLightsaberType(lightsaberColor);
lightsaberType.Dump($"Given to {name}");
Council.Add(new Jedi(name, lightsaberType));
}
}
// Flyweight objects' pool - Creates the flyweight items and caches them
public static class LightsaberFactory
{
private static IDictionary<string, LightsaberType> _cache
= new Dictionary<string, LightsaberType>();
public static LightsaberType GetLightsaberType(string color)
{
if (!_cache.ContainsKey(color))
{
$"Creating a {color} lightsaber".Dump();
_cache.Add(color, new LightsaberType(color));
}
return _cache[color];
}
}
// Flyweight object - Manages its intrinsic state, must be immutable
public record LightsaberType(string Color);
// Context object - Depends on a flyweight item and providing an extrinsic state that
// can vary independently of the flyweight object
public class Jedi
{
string _name;
LightsaberType _type;
public Jedi(string name, LightsaberType type)
=> (_name, _type) = (name, type);
}