C# 设计模式 结构型模式 之 享元模式

享元模式 主要用于减少创建对象的数量,以减少内存占用和提高性能。这种类型的设计模式属于结构型模式,它提供了减少对象数量从而改善应用所需的对象结构的方式。享元模式尝试重用现有的同类对象,如果未找到匹配的对象,则创建新对象。

解决意图:在有大量对象时,有可能会造成内存溢出,我们把其中共同的部分抽象出来,如果有相同的业务请求,直接返回在内存中已有的对象,避免重新创建。

优点:大大减少对象的创建,降低系统的内存,使效率提高。

下面通过 案例解析下 享元模式:

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;
        }
    }
}

缺点:提高了系统的复杂度,需要分离出外部状态和内部状态,而且外部状态具有固有化的性质,不应该随着内部状态的变化而变化,否则会造成系统的混乱。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值