c#设计模式之享元模式

享元模式使用共享对象可有效的支持大量的细粒度的对象

类图如下:


Flyweight

public abstract class Flyweight
    {
        public string intrinsic;
        public string extrinsic;
        public Flyweight(string extrinsic)
        {
            this.extrinsic = extrinsic;
        }
        public void SetIntrinsic(string intrinsic)
        {
            this.intrinsic = intrinsic;
        }
        public string GetIntrinsic()
        {
            return intrinsic;
        }

    }

ConcreteFlyweight

 public class ConcreteFlyweight : Flyweight
    {
        public ConcreteFlyweight(string extrinsic) : base(extrinsic)
        {

        }
    }

FlyweightFactory

public class FlyweightFactory
    {
        private static Dictionary flyweights = new Dictionary();
        public static Flyweight GetFlyweight(string extrinsic)
        {
            if(flyweights.ContainsKey(extrinsic))
            {
                Flyweight one = null;
                flyweights.TryGetValue(extrinsic,out one);
                return one;
            }
            else
            {
                Flyweight one = new ConcreteFlyweight(extrinsic);
                flyweights.Add(extrinsic, one);
                return one;
            }
        }
    }

调用

static void Main(string[] args)
        {
            Flyweight flyweight = FlyweightFactory.GetFlyweight("x");
            Flyweight flyweight1 = FlyweightFactory.GetFlyweight("x");
        }

优点:

  1. 节省内存空间
  2. 提高创建效率

缺点:

  1. 提高了复杂性,分离出了内部状态和外部状态(可以共享的状态)

源代码地址: 点击我下载 提取码: 6qh7

你可能感兴趣的:(c#设计模式之享元模式)