享元模式 主要用于减少创建对象的数量,以减少内存占用和提高性能。这种类型的设计模式属于结构型模式,它提供了减少对象数量从而改善应用所需的对象结构的方式。享元模式尝试重用现有的同类对象,如果未找到匹配的对象,则创建新对象。
解决意图:在有大量对象时,有可能会造成内存溢出,我们把其中共同的部分抽象出来,如果有相同的业务请求,直接返回在内存中已有的对象,避免重新创建。
优点:大大减少对象的创建,降低系统的内存,使效率提高。
下面通过 案例解析下 享元模式:
namespace 享元模式
{
internal class Program
{
static void Main(string[] args)
{
Circle shapeRed = (Circle)CircleFactory.GetCircle("红色");
shapeRed.SetX(10);
shapeRed.SetY(20);
shapeRed.SetRadius(10);
shapeRed.Draw();
/*控制台 打印:
*
* 颜色为:红色
红色的圆radius为:10x为:10y为:20
*/
}
}
public interface Shape
{
void Draw();
}
//实现 并 扩展 Shape类
public class Circle : Shape
{
private string color;
private int radius;
private int x;
private int y;
public Circle(string color)
{
this.color = color;
}
public void SetX(int x)
{
this.x = x;
}
public void SetY(int y)
{
this.y = y;
}
public void SetRadius(int radius)
{
this.radius = radius;
}
public void Draw()
{
Console.WriteLine(color+"的圆radius为:"+radius+"x为:"+x+"y为:"+y);
}
}
//实现享元模式 :创建 工厂 如果 Circle为空 新建 Circle,否则 返回 内存中 Circle缓存
public class CircleFactory
{
private static Dictionary<string, Shape> circles = new Dictionary<string, Shape>();
public static Shape GetCircle(string color)
{
Shape? shape=null;
try
{
shape = circles[color];
}
catch(Exception ex){}
if (shape == null)
{
shape = new Circle(color);
circles.Add(color, shape);
Console.WriteLine("颜色为:" + color);
}
return shape;
}
}
}
缺点:提高了系统的复杂度,需要分离出外部状态和内部状态,而且外部状态具有固有化的性质,不应该随着内部状态的变化而变化,否则会造成系统的混乱。