Flyweight享元模式
Flyweight享元模式是避免系统过多出现重复实例,同样的对象公用一个元,如下图所示:
以一个系统中一个文档中,有很多字,每个字有相应的字体,如果对每个字设置字体就如箭头前的模式.箭头后面是Flyweight模式结构,代码如下:
Flyweight
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
class Font//12bytes+8bytes(4byte抽象对象,还有4byte垃圾回收等,继承object对象) =
{
string frontName;//4bytes
int size;//4bytes
Color color;//4bytes
//重写Front.Equals
}
class Charactor //(2+4+20+2) + 8byte = 36
{
public char chr; //16 bit,2bytes,
public Font f;
public static HashTablle frontTable;
//public void SetFront(string name, int size, Color color)
//{
// Font f = new Font(name, size, color);
// if(frontTable.Keys.Exist(f))
// {
// return frontTable.Keys[f];
// }
// else
// {
// frontTable.Keys.Add(f);
// }
//}
public Font CFront
{
get
{
return f;
}
set
{
if (frontTable.Keys.Exist(f))
{
this.f = frontTable.Keys[f];
}
else
{
frontTable.Keys.Add(value);
this.f = value;
}
}
}
}
class System
{
public static void Main()
{
//36byte*100000 = 3600000bytes = 3600k => 3.6M
ArrayList list = new ArrayList(100000);
Font f1 = new Font("宋体",5,Color.Red);
Font f2 = new Font("宋体", 5,Color.Red);
Charactor c = new Charactor();
c.chr = 'a';
c.CFront = f1;
Charactor c2 = new Charactor();
c2.chr = 'a';
c2.CFront = f2;
for (int i = 0; i < list.Count; i++)
{
Charactor c = new Charactor();
c.chr = 'a';
c.CFront = new Font();
}
list.Add(c);
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
class Font//12bytes+8bytes(4byte抽象对象,还有4byte垃圾回收等,继承object对象) =
{
string frontName;//4bytes
int size;//4bytes
Color color;//4bytes
//重写Front.Equals
}
class Charactor //(2+4+20+2) + 8byte = 36
{
public char chr; //16 bit,2bytes,
public Font f;
public static HashTablle frontTable;
//public void SetFront(string name, int size, Color color)
//{
// Font f = new Font(name, size, color);
// if(frontTable.Keys.Exist(f))
// {
// return frontTable.Keys[f];
// }
// else
// {
// frontTable.Keys.Add(f);
// }
//}
public Font CFront
{
get
{
return f;
}
set
{
if (frontTable.Keys.Exist(f))
{
this.f = frontTable.Keys[f];
}
else
{
frontTable.Keys.Add(value);
this.f = value;
}
}
}
}
class System
{
public static void Main()
{
//36byte*100000 = 3600000bytes = 3600k => 3.6M
ArrayList list = new ArrayList(100000);
Font f1 = new Font("宋体",5,Color.Red);
Font f2 = new Font("宋体", 5,Color.Red);
Charactor c = new Charactor();
c.chr = 'a';
c.CFront = f1;
Charactor c2 = new Charactor();
c2.chr = 'a';
c2.CFront = f2;
for (int i = 0; i < list.Count; i++)
{
Charactor c = new Charactor();
c.chr = 'a';
c.CFront = new Font();
}
list.Add(c);
}
}