# 享元模式

属于结构型模式。
运用共享技术有效地支持大量细粒度的对象。

享元模式可以避免大量非常相似类的开销。如果能把那些不同的参数移到类实例的外面,在方法调用时将他们传递进来,就可以通过共享大幅度减少单个实例的数目。

在 CSharp 中,string 就是运用了享元模式。例:声明两个字符串 string A = "A"; string B = "A"; 使用 Object.ReferenceEquals (A, B); 检查 A 和 B 是否是相同的实例,结果:true

# 类图

img

# 代码

# 不相同的部分

namespace StructuralPattern_FlyweightPattern
{
    /// <summary>
    /// 颜色
    /// </summary>
    public class Color
    {
        public string ColorName;
        public Color(string colorName)
        {
            ColorName = colorName;
        }
    }
}

# 相同的部分

namespace StructuralPattern_FlyweightPattern
{
    /// <summary>
    /// 形状
    /// </summary>
    public abstract class Shape
    {
        public Color MyColor;
        /// <summary>
        /// 形状
        /// </summary>
        public abstract void MyShape();
    }
}
namespace StructuralPattern_FlyweightPattern
{
    /// <summary>
    /// 正方形
    /// </summary>
    public class Square : Shape
    {
        public override void MyShape()
        {
            Console.WriteLine("Shape: Square\nColor: " + MyColor.ColorName);
        }
    }
}

# 享元工厂

namespace StructuralPattern_FlyweightPattern
{
    public class FlyweightFactory
    {
        private Dictionary<string, Shape> ShapeDic;
        public FlyweightFactory()
        {
            ShapeDic = new Dictionary<string, Shape>();
        }
        /// <summary>
        /// 获取 Shape 类的实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="name"></param>
        /// <returns></returns>
        public Shape GetShape<T>(string name) where T : Shape
        {
            if (ShapeDic.ContainsKey(name))
            {
                return ShapeDic[name];
            }
            else
            {
                T temp = Activator.CreateInstance(typeof(T)) as T;
                ShapeDic.Add(name, temp);
                return temp;
            }
        }
    }
}

# 测试

namespace StructuralPattern_FlyweightPattern
{
    public class Program
    {
        private static void Main()
        {
            FlyweightFactory factory = new FlyweightFactory();
            Shape shape_0 = factory.GetShape<Square>("Square");
            shape_0.MyColor = new Color("Red");
            shape_0.MyShape();
            Console.WriteLine();
            // 此时,shape_0 和 shape_1 是同一个实例
            Shape shape_1 = factory.GetShape<Square>("Square");
            shape_1.MyColor = new Color("Blue");
            shape_1.MyShape();
        }
    }
}

运行结果:
Shape: Square
Color: Red

Shape: Square
Color: Blue

更新于 阅读次数

请我喝[茶]~( ̄▽ ̄)~*

Maikire 微信支付

微信支付

Maikire 支付宝

支付宝

Maikire 贝宝

贝宝