-
简介
运用共享技术有效的支持大量细粒度的对象 -
应用:当一个应用使用了大量的对象,而大量的这些对象造成了很大的存储开销的时候就应该使用,还有就是对象的大多数状态可以外部状态,如果删除对象的外部状态,那么可以用相对较少的共享对象取代很多组对象,此时可以考虑使用享元模式。
-
代码
//享元类的接口或者超累
abstract class Flyweight
{
public abstract void Operation(int extrinsicstate);
}
//具体的实现子类
class ConcreteFlyweight :Flyweight
{
private string name ="";
public ConcreteFlyweight(string name){
this.name = name;
}
public override void Operation(int extrinsicstate)
{
Console.WriteLine("具体 Flyweight:"+extrinsicstate);
}
}
//不共享的子类,不共享类的存在是因为有些数据是不需要共享的。
class UnsharedConcreteFlyweight :Flyweight
{
public override void Operation(int extrinsicstate)
{
Console.WriteLine("不共享的具体 Flyweight:"+extrinsicstate);
}
}
//享元工厂类,创建并管理 Flyweight 对象
class FlyweightFactory
{
private Hashtable flyweights = new Hashtable();
public Flyweight GetFlyweight(string key)
{
if(!flyweights.ContainsKey(key))
flyweights.Add(key,new ConcreteFlyweight(key))
}
return (Flyweight)flyweights(key);
}
}
//客户端调用
static void Main(string[] args){
int num = 22;
FlyweightFactory f = new FlyweightFactory();
Flyweight fx = f.GetFlyweight("X");
fx.Operation(--num);
Flyweight fy = f.GetFlyweight("Y");
fy.Operation(--num);
Flyweight uf = new UnsharedConcreteFlyweight();
uf.Operation(--num);
Console.Read();
}
网友评论