享元模式:主要用于减少创建对象的数量,以减少内存占用和提高性能。这种类型的设计模式属于结构型模式,它提供了减少对象数量从而改善应用所需的对象结构的方式。
主要意图:运用共享技术有效地支持大量细粒度的对象。
主要解决:在有大量对象时,有可能会造成内存溢出,我们把其中共同的部分抽象出来,如果有相同的业务请求,直接返回在内存中已有的对象,避免重新创建。
解决方案:用唯一标识码判断,如果在内存中有,则返回这个唯一标识码所标识的对象。
优点:
1,大大减少对象的创建,降低系统的内存,使效率提高。
缺点:
1,提高了系统的复杂度。需要分离出内部状态和外部状态,而外部状态具有固化特性,不应该随着内部状态的改变而改变。
享元模式类图:
代码实现:
客户端代码:
using System; namespace _02享元模式_结构图 { 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"); fy.Operation(--extrinsicstate); Flyweight fz = f.GetFlyweight("Z"); fz.Operation(--extrinsicstate); Flyweight uf = new UnsharedConcreteFlyweight(); uf.Operation(--extrinsicstate); Console.Read(); } } }
抽象享元角色:
using System; using System.Collections.Generic; using System.Text; namespace _02享元模式_结构图 { abstract class Flyweight { public abstract void Operation(int extrinsicstate); } }
具体享元角色:
using System; using System.Collections.Generic; using System.Text; namespace _02享元模式_结构图 { class ConcreteFlyweight:Flyweight { public override void Operation(int extrinsicstate) { Console.WriteLine("具体Flyweight:" + extrinsicstate) ; } } }
享元工厂:
using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace _02享元模式_结构图 { 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]); } } }
独享具体享元角色:
using System; using System.Collections.Generic; using System.Text; namespace _02享元模式_结构图 { class UnsharedConcreteFlyweight:Flyweight { public override void Operation(int extrinsicstate) { Console.WriteLine("不共享的具体Flyweight:" + extrinsicstate) ; } } }
