设计模式 - 享元模式(Flyweight Pattern)
随着面向对象技术的应用普及和成熟,使其在解决一些扩展性和灵活性的问题上表现出色。但是随着系统的复杂性的增加,系统新增的类和其对象也是日渐增多,当对象数量过多时,会占用大量内存空间,导致运行代价过高,系统性能下降问题。
享元模式的诞生就是为了解决这些问题。通过共享技术重用相似或者类似的对象,可以共享的相同内容称为内部状态;需要外部环境来设置的不能共享的称为外部状态。享元模式中会使用到工厂模式,来创建和维护对象池(享元池)来存储具有相同状态的享元对象。
那什么是享元模式呢?
享元模式 - 运用共享技术有效支持细粒度的对象的复用。系统只使用少量的对象。而这些对象都很相似,状态变化很小,可以实现对象的多次复用。由于享元模式要求能够共享的对象必须是细粒度对象,因此它又称为轻量级模式,它是一种对象结构型模式。以下是其UML类图
优点
减少创建内存开销,节省内存空间,提高程序运行效率
缺点
提高了系统的复杂度,需要分离出外部状态和内部状态,而且外部状态具有固有化的性质,不应该随着内部状态的变化而变化,否则会造成系统的混乱。
FlyWeightFactory: 享元对象工厂,负责维护享元模式对象
FlyWeight: 抽象类或者接口
ConcreteFlyWeight 具体享元类
下面是享元模式的例子
namespace ConsoleApp3.Flyweight { /// <summary> /// Abstract flyweight class /// </summary> public interface IFlyweight { void Update(); } }
ConcreteFlyweight1
using System; namespace ConsoleApp3.Flyweight { public class ConcreteFlyWeight1 : IFlyweight { public ConcreteFlyWeight1(FlyWeightFactory flyWeightFactory) { flyWeightFactory.Attach(this); } public void Update() { Console.WriteLine("execute ConcreteFlyWeight1"); } } }
ConcreteFlyweight2
using System; namespace ConsoleApp3.Flyweight { public class ConcreteFlyWeight2 : IFlyweight { public ConcreteFlyWeight2(FlyWeightFactory flyWeightFactory) { flyWeightFactory.Attach(this); } public void Update() { Console.WriteLine("execute ConcreteFlyWeight2"); } } }
FlyWeightFactory
using System.Collections.Generic; using System.Linq; namespace ConsoleApp3.Flyweight { public class FlyWeightFactory { private List<IFlyweight> flyweights = new List<IFlyweight>(); public void Attach(IFlyweight flyweight) { if (!flyweights.Contains(flyweight)) { flyweights.Add(flyweight); } }
public IFlyweight GetFlyweight(Type type)
{
return flyweights.FirstOrDefault(p => p.GetType() == type);
}
}
}
Demo
FlyWeightFactory factory = new FlyWeightFactory();
var flyweightO = factory.GetFlyweight(typeof(ConcreteFlyWeight1));
flyweightO.Update();
var flyweightT = factory.GetFlyweight(typeof(ConcreteFlyWeight2));
flyweightT.Update();
运行结果