设计模式实践-享元模式

场景

通过享元模式获取仪表对象

实现代码

享元接口

namespace DesignPatterns.Flyweight
{
    /// <summary>
    /// 仪表享元接口
    /// </summary>
    public interface IFlyweight
    {
        /// <summary>
        /// 业务逻辑
        /// </summary>
        void Do();
    }
}

仪表对象

namespace DesignPatterns.Flyweight
{
    /// <summary>
    /// 仪表享元对象
    /// </summary>
    public class MeterFlyweight : IFlyweight
    {
        /// <summary>
        /// 外部状态id
        /// </summary>
        private string _idShare;

        /// <summary>
        /// 内部状态id
        /// </summary>
        private int _id;

        /// <summary>
        ///  Initializes a new instance of the <see cref="MeterFlyweight" /> class.
        /// </summary>
        /// <param name="id">仪表id</param>
        public MeterFlyweight(int id)
        {
            this._id = id;
            this._idShare = string.Format($"{id}_share");
            Console.WriteLine($"in MeterFlyweight, id: {this._id}");
        }

        /// <summary>
        /// 获取外部状态ID
        /// </summary>
        public string GetShareId => this._idShare;

        /// <summary>
        /// 获取内部状态ID
        /// </summary>
        public int GetId => this._id;

        /// <summary>
        /// 业务逻辑
        /// </summary>
        public void Do()
        {
            Console.WriteLine($"The id of meter is {this._id}");
        }
    }
}

非共享对象

namespace DesignPatterns.Flyweight
{
    /// <summary>
    /// 非共享仪表对象
    /// </summary>
    public class UnsharedMeterFlyweight : IFlyweight
    {
        /// <summary>
        /// 业务逻辑
        /// </summary>
        public void Do()
        {
            Console.WriteLine($"Unshared meter.");
        }
    }

享元工厂

namespace DesignPatterns.Flyweight
{
    /// <summary>
    /// 享元工厂
    /// </summary>
    public class FlyweightFactory
    {
        /// <summary>
        /// 享元集合
        /// </summary>
        private Dictionary<string, IFlyweight> _flyweights = new Dictionary<string, IFlyweight>();

        /// <summary>
        /// 获取享元仪表
        /// </summary>
        /// <param name="id">仪表ID</param>
        /// <returns>享元仪表接口</returns>
        public IFlyweight GetMeter(int id)
        {
            IFlyweight meter = null;
            if (!this._flyweights.TryGetValue($"{id}_share", out meter))
            {
                meter = new MeterFlyweight(id);
                this._flyweights.Add(((MeterFlyweight)meter).GetShareId, meter);
            }

            return meter;
        }
    }
}

相关调用

FlyweightFactory factory = new FlyweightFactory();
var meter1 = factory.GetMeter(1);
meter1.Do();
var meter2 = factory.GetMeter(2);
meter2.Do();
var meter3 = factory.GetMeter(3);
meter3.Do();
var meter4 = factory.GetMeter(1);
meter4.Do();

Out

in MeterFlyweight, id: 1
The id of meter is 1
in MeterFlyweight, id: 2
The id of meter is 2
in MeterFlyweight, id: 3
The id of meter is 3
The id of meter is 1
posted @ 2016-07-21 20:35  4Thing  阅读(148)  评论(0编辑  收藏  举报