0%

设计模式-享元模式

用于减少创建对象的数量,以减少内存占用和提高性能
运用共享技术有效地支持大量细粒度的对象
在有大量对象时,有可能会造成内存溢出,我们把其中共同的部分抽象出来,如果有相同的业务请求,直接返回在内存中已有的对象,避免重新创建
用 HashMap(Hashtable) 存储这些对象

string 运用了Flyweight模式

享元模式

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
//Flyweight 享元接口
abstract class Flyweight
{
public abstract void Operation(int extrinsicstate);
}
//共享的Flyweight子类
class ConcreateFlyweight : Flyweight
{
public override void Operation(int extrinsicstate)
{
Console.WriteLine("具体Flayweight: " + extrinsicstate);
}
}
//不需要共享的Flyweight子类
class UnsharedConcreateFlyweight : Flyweight
{
public override void Operation(int extrinsicstate)
{
Console.WriteLine("不共享的具体Flayweight: " + extrinsicstate);
}
}
//享元工厂
class FlyweightFactory
{
private Hashtable flyweights = new Hashtable();
public FlyweightFactory()
{
flyweights.Add("X", new ConcreateFlyweight());
flyweights.Add("Y", new ConcreateFlyweight());
flyweights.Add("X", new ConcreateFlyweight());
}
public Flyweight GetFlyweight(string key)
{
if(!flyweights.ContainKey(key))
flyweights.Add(key, new ConcreateFlyweight());
return(Flyweight)flyweight[key];
}
}
//Client
int extrinsicstate = 22;
FlyweightFactory f = new FlyweightFactory();
Flyweight fx = f.GetFlyweight("X");
fx.Operation(--extrinsicstate);
Flyweight fy = f.GetFlyweight("Y");
fy.Operation(--extrinsicstate);
Flyweight fz = f.GetFlyweight("Z");
fz.Operation(--extrinsicstate);

Flyweight uf = new UnsharedConcreateFlyweight();
uf.Operation(--extrinsicstate);