-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathFlyweightPattern.cs
More file actions
129 lines (113 loc) · 3.17 KB
/
FlyweightPattern.cs
File metadata and controls
129 lines (113 loc) · 3.17 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace FlyweightPattern
{
public class FlyweightPattern : MonoBehaviour
{
void Start()
{
string document = "AAZZBBZB";
char[] chars = document.ToCharArray();
CharacterFactory factory = new CharacterFactory();
// 外在状态
int pointSize = 10;
foreach (char c in chars)
{
pointSize++;
Character character = factory.GetCharacter(c);
character.Display(pointSize);
}
}
}
class CharacterFactory
{
private Dictionary<char, Character> _characters =
new Dictionary<char, Character>();
public Character GetCharacter(char key)
{
Character character = null;
if (_characters.ContainsKey(key))
{
character = _characters[key];
}
else
{
switch (key)
{
case 'A': character = new CharacterA(); break;
case 'B': character = new CharacterB(); break;
//...
case 'Z': character = new CharacterZ(); break;
}
_characters.Add(key, character);
}
return character;
}
}
// Character类型所有的数据(外在 + 内在)
abstract class Character
{
protected char symbol;
protected int width;
protected int height;
protected int ascent;
protected int descent;
protected int pointSize;
public abstract void Display(int pointSize);
}
class CharacterA : Character
{
public CharacterA()
{
// CharacterA 共享的类型
this.symbol = 'A';
this.height = 100;
this.width = 120;
this.ascent = 70;
this.descent = 0;
}
public override void Display(int pointSize)
{
this.pointSize = pointSize;
Debug.Log(this.symbol +
" (pointsize " + this.pointSize + ")");
}
}
class CharacterB : Character
{
public CharacterB()
{
// CharacterB 共享的类型
this.symbol = 'B';
this.height = 100;
this.width = 140;
this.ascent = 72;
this.descent = 0;
}
public override void Display(int pointSize)
{
this.pointSize = pointSize;
Debug.Log(this.symbol +
" (pointsize " + this.pointSize + ")");
}
}
// ... C, D, E, etc.
class CharacterZ : Character
{
public CharacterZ()
{
// CharacterZ 共享的类型
this.symbol = 'Z';
this.height = 100;
this.width = 100;
this.ascent = 68;
this.descent = 0;
}
public override void Display(int pointSize)
{
this.pointSize = pointSize;
Debug.Log(this.symbol + " (pointsize " + this.pointSize + ")");
}
}
}