享元模式解决由于存在大量的细粒度对象而造成不必要的内存开销的问题,它与外观模式恰好相反,关注的重点是细小的对象。
享元对象共享是要区分内部状态和外部状态,内部对象不随环境的变化,可以共享;外部对象通常是由客户端调用的时候传递的,不共享。
享元模式角色:
◊Flyweight:声明一个接口,来接收并作用于外部状态。
◊ConcreteFlyweight:实现Flyweight接口,为内部状态增加存储空间。ConcreteFlyweight对象是可以共享的,它所存储的状态必须是内部的,即它独立于具体对象的场景。
◊UnsharedConcreteFlyweight:并不是所有的Flyweight子类都需要被共享。在Flyweight对象结构的某些层次,UnsharedConcreteFlyweight对象通常将ConcreteFlyweight对象作为子节点,该对象也可以没有。
◊FlyweightFactory:创建和管理flyweight对象。
装饰模式适用情形:
◊ 在有大量对象时,有可能会造成内存溢出,我们把其中共同的部分抽象出来,如果有相同的业务请求,直接返回在内存中已有的对象,避免重新创建。
结构图:
namespace Libraries.Test.DesignPattern.Flyweight
{
public interface IShape
{
string Draw(int x, int y, int length);
}
}
namespace Libraries.Test.DesignPattern.Flyweight
{
/// <summary>
/// 画直线
/// </summary>
public class Line : IShape
{
//颜色为享元对象
private String color;
public Line(string color)
{
this.color = color;
}
public string Draw(int x, int y, int length)
{
return "画直线:颜色:" + this.color + ",起点坐标[" + x + "," + y + "],长度:" + length + "";
}
}
}
namespace Libraries.Test.DesignPattern.Flyweight
{
public class ShapeFactory
{
private IDictionary<string, IShape> dictShape = new Dictionary<string, IShape>();
public ShapeFactory()
{
dictShape.Add("红色", new Line("红色"));
dictShape.Add("绿色", new Line("绿色"));
dictShape.Add("蓝色", new Line("蓝色"));
}
/// <summary>
/// 画直线
/// </summary>
/// <param name="color"></param>
/// <returns></returns>
public IShape getLine(string color)
{
IShape shape = dictShape[color];
if (shape == null)
{
shape = new Line(color);
dictShape.Add(color, shape);
}
return shape;
}
}
}
namespace Libraries.Test.DesignPattern.Flyweight
{
public class Client
{
public void Excute()
{
ShapeFactory shapeFactory = new ShapeFactory();
//共享对象
IShape shape = shapeFactory.getLine("红色");
//非共享对象
string strLine = shape.Draw(25, 35, 100);
}
}
}