结构型设计模式之享元模式(Flyweight)

结构 结构型设计模式之享元模式(Flyweight)
意图 运用共享技术有效地支持大量细粒度的对象。
适用性
  • 一个应用程序使用了大量的对象。
  • 完全由于使用大量的对象,造成很大的存储开销。
  • 对象的大多数状态都可变为外部状态。
  • 如果删除对象的外部状态,那么可以用相对较少的共享对象取代很多组对象。
  • 应用程序不依赖于对象标识。由于F l y w e i g h t 对象可以被共享,对于概念上明显有别的对象,标识测试将返回真值。
  using System;
using System.Collections; class FlyweightFactory
{
private ArrayList pool = new ArrayList(); // the flyweightfactory can crete all entries in the pool at startup
// (if the pool is small, and it is likely all will be used), or as
// needed, if the pool si large and it is likely some will never be used
public FlyweightFactory()
{
pool.Add(new ConcreteEvenFlyweight());
pool.Add(new ConcreteUnevenFlyweight());
} public Flyweight GetFlyweight(int key)
{
// here we would determine if the flyweight identified by key
// exists, and if so return it. If not, we would create it.
// As in this demo we have implementation all the possible
// flyweights we wish to use, we retrun the suitable one.
int i = key % ;
return((Flyweight)pool[i]);
}
} abstract class Flyweight
{
abstract public void DoOperation(int extrinsicState);
} class UnsharedConcreteFlyweight : Flyweight
{
override public void DoOperation(int extrinsicState)
{ }
} class ConcreteEvenFlyweight : Flyweight
{
override public void DoOperation(int extrinsicState)
{
Console.WriteLine("In ConcreteEvenFlyweight.DoOperation: {0}", extrinsicState);
}
} class ConcreteUnevenFlyweight : Flyweight
{
override public void DoOperation(int extrinsicState)
{
Console.WriteLine("In ConcreteUnevenFlyweight.DoOperation: {0}", extrinsicState);
}
} /// <summary>
/// Summary description for Client.
/// </summary>
public class Client
{
public static int Main(string[] args)
{
int[] data = {,,,,,,,}; FlyweightFactory f = new FlyweightFactory(); int extrinsicState = ;
foreach (int i in data)
{
Flyweight flyweight = f.GetFlyweight(i);
flyweight.DoOperation(extrinsicState);
} return ;
}
}

享元模式

上一篇:关于基因组注释文件GTF的解释


下一篇:Centos中的Docker 配置:将loop-lvm改为derict-lvm