享元模式(Flyweight):运用共享技术有效地支持大量细粒度的对象。享元模式可以避免大量相似类的开销。在程序设计中,有时需要生成大量细粒度的类实现来表示数据。如果能发现这些实例除了几个参数外基本上都是相同的有时就能够大幅度地减少需要实例化的类的数量。如果能把那些参数移到类实例的外面,在方法调用时将它们传递进来,就可以通过共享大幅度地减少单个实例的数目。
- using System;
- using System.Collections;
- using System.Collections.Generic;
- namespace StuDesignMode.Fryweight
- {
- abstract class AbsFlyweight
- {
- public abstract void Operation(int extrinsicstate);
- }
- class ConcreteFlyweight : AbsFlyweight
- {
- public override void Operation(int extrinsicstate)
- {
- Console.WriteLine("具体Flyweight:"+ extrinsicstate);
- }
- }
- class UnsharedConcreteFlyweight : AbsFlyweight
- {
- 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 AbsFlyweight GetFlyweight(string key)
- {
- return (AbsFlyweight)flyweights[key];
- }
- }
- class ClientTest
- {
- static void Main(string[] ages)
- {
- int ex = 22;
- FlyweightFactory f = new FlyweightFactory();
- AbsFlyweight fx = f.GetFlyweight("x");
- fx.Operation(--ex);
- AbsFlyweight fy = f.GetFlyweight("y");
- fy.Operation(--ex);
- AbsFlyweight fz = f.GetFlyweight("z");
- fz.Operation(--ex);
- UnsharedConcreteFlyweight sh = new UnsharedConcreteFlyweight();
- sh.Operation(--ex);
- Console.WriteLine();
- }
- }
- }