享元模式:运用共享技术有效地支持大量细粒度的对象
FlyweightFactory(工厂类)
负责产生和管理Flyweight的组件
内部通常使用容器类来存储共享的Flyweight组件
提供工厂方法产生对应的组件,当产生的是共享组件时,就加入到Flyweight管理容器内
Flyweight(组件接口)
定义组件的操作接口
ConcreteFlyweight(可以共享的组件)
实现Flyweight接口
产生的组件时可以共享的,并加入到Flyweight管理器中
UnsharedConcreteFlyweight(不可以共享的组件)
实现Flyweight接口,也可以选择不继承自Flyweight接口
可以定义为单独的组件,不包含任何共享资源
也可以讲一些共享组件定义为类的成员,成为内部状态;并另外定义其他不被共享的成员,作为外部状态使用
csharp
class Program
{
static void Main(string[] args)
{
int extrinsicstate = 25;
FlyweightFactory f = new FlyweightFactory();
Flyweight fx = f.GetFlyweight("X");
fx.Operation(--extrinsicstate);
Flyweight fy = f.GetFlyweight("Y");
fx.Operation(--extrinsicstate);
Flyweight fz = f.GetFlyweight("Z");
fx.Operation(--extrinsicstate);
Flyweight uf = new UnsharedConcreteFlyweight();
uf.Operation(--extrinsicstate);
Console.ReadLine();
}
}
abstract class Flyweight
{
public abstract void Operation(int extrinsicstate);
}
class ConcreteFlyweight : Flyweight
{
public override void Operation(int extrinsicstate)
{
Console.WriteLine("具体Flyweight:"+extrinsicstate);
}
}
class UnsharedConcreteFlyweight : Flyweight
{
public override void Operation(int extrinsicstate)
{
Console.WriteLine("不共享的具体Flyweight:"+extrinsicstate);
}
}
class FlyweightFactory
{
private Hashtable flyweights = new Hashtable();
public FlyweightFactory()
{
flyweights.Add("X", new ConcreteFlyweight());
flyweights.Add("Y", new ConcreteFlyweight());
flyweights.Add("Z", new ConcreteFlyweight());
}
public Flyweight GetFlyweight(string key)
{
return ((Flyweight)flyweights[key]);
}
}
享元模式的实例
csharp
class Program
{
static void Main(string[] args)
{
WebSiteFactory f = new WebSiteFactory();
WebSite fx = f.GetWebSiteCategory("网页");
fx.Use();
WebSite fy = f.GetWebSiteCategory("网页");
fy.Use();
WebSite fz = f.GetWebSiteCategory("网页");
fz.Use();
WebSite f1 = f.GetWebSiteCategory("博客");
f1.Use();
WebSite f2 = f.GetWebSiteCategory("博客");
f2.Use();
WebSite f3 = f.GetWebSiteCategory("博客");
f3.Use();
Console.WriteLine("网站分类总数为{0}",f.GetWebSiteCount());
Console.ReadLine();
}
}
abstract class WebSite
{
public abstract void Use();
}
class ConcreteWebSite : WebSite
{
private string name = "";
public ConcreteWebSite(string name)
{
this.name = name;
}
public override void Use()
{
Console.WriteLine("网络分类:"+name);
}
}
class WebSiteFactory
{
private Hashtable flyweights = new Hashtable();
//获得网站分类
public WebSite GetWebSiteCategory(string key)
{
if (!flyweights.ContainsKey(key))
{
flyweights.Add(key, new ConcreteWebSite(key));
}
return ((WebSite)flyweights[key]);
}
//获得网站分离总数
public int GetWebSiteCount()
{
return flyweights.Count;
}
}