代码改变世界

设计模式之享元模式(Flyweight)

2010-01-23 17:56  key_sky  阅读(313)  评论(0编辑  收藏  举报

享元模式(Flyweight):运用共享技术有效地支持大量细粒度的对象。
Flyweight:所有具体享元类的超类或接口,通过这个接口,Flyweight可以接受并作用于外部状态
ConcreteFlyweight:继承Flyweight超类或实现Flyweight接口,并为内部状态增加存储空间。
UnsharedConcreteFlyweight:不需要共享的Flyweight子类。因为Flyweight接口共享成为可能,但不强制共享.
FlyweightFactory:享元工厂,用来创建并管理Flyweight对象。主要用来确保合理并共享Flyweight当用户请求一个Flyweight时,FlyweightFactory对象提供一个已创建的实例或者创建一个。
使用范围:1.如果一个应用程序使用了大量的对象,而大量的这些对象造成了很大的存储开销
2.对象的大多数状态可以外部状态,如果删除对象的外部状态,那么可以用相对较少的共享对象取代

Flyweight1.cs

代码
using System;
using System.Data;
using System.Configuration;
using System.Collections;

//享元模式(Flyweight):运用共享技术有效地支持大量细粒度的对象。
//Flyweight:所有具体享元类的超类或接口,通过这个接口,Flyweight可以接受并作用于外部状态
//ConcreteFlyweight:继承Flyweight超类或实现Flyweight接口,并为内部状态增加存储空间。
//UnsharedConcreteFlyweight:不需要共享的Flyweight子类。因为Flyweight接口共享成为可能,但不
//强制共享.
//FlyweightFactory:享元工厂,用来创建并管理Flyweight对象。主要用来确保合理并共享Flyweight
//当用户请求一个Flyweight时,FlyweightFactory对象提供一个已创建的实例或者创建一个。
//使用范围:1.如果一个应用程序使用了大量的对象,而大量的这些对象造成了很大的存储开销
//2.对象的大多数状态可以外部状态,如果删除对象的外部状态,那么可以用相对较少的共享对象取代
namespace Flyweight
{
class Flyweight1
{
}
//Flyweight
abstract class Flyweight
{
public abstract void Operation(int extrinsicstate);
}
//ConcreteFlyweight
class ConcreteFlyweight : Flyweight
{
public override void Operation(int extrinsicstate)
{
Console.WriteLine(
"具体Flyweight" + extrinsicstate);
}
}
//UnshareConcreteFlyweight
class UnshareConcreteFlyweight : Flyweight
{
public override void Operation(int extrinsicstate)
{
Console.WriteLine(
"不共享的具体Flyweight:" + extrinsicstate);
}
}
//FlyweightFactory
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]);
}
}
}

 

Program.cs

代码
using System;
using System.Collections.Generic;
using System.Text;

namespace Flyweight
{
class Program
{
static void Main(string[] args)
{
int extrinsicstate = 22;

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");
fz.Operation(
--extrinsicstate);

Flyweight ur
= new UnshareConcreteFlyweight();

ur.Operation(
--extrinsicstate);

Console.Read();
}
}
}

 

运行结果:

具体Flyweight21

具体Flyweight20

具体Flyweight19

不共享的具体Flyweight:18