享元模式使用共享对象可有效的支持大量的细粒度的对象
类图如下:
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<string, Flyweight> flyweights = new Dictionary<string, Flyweight>();
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");
}
优点:
- 节省内存空间
- 提高创建效率
缺点:
- 提高了复杂性,分离出了内部状态和外部状态(可以共享的状态)
源代码地址: 点击我下载 提取码: 6qh7