极速理解设计模式系列:14.轻量级模式(Flyweight Pattern)

五个角色:抽象轻量级类(Flyweight)、具体轻量级类(ConcreteFlyweight)、不共享具体轻量级类(UnsharedConcreteFlyweight)、轻量级类工厂(FlyweightFactory)、客户端(Client) 

        抽象轻量级类(Flyweight):声明一个接口并且有一些属性可以设置对象的状态

        具体轻量级类(ConcreteFlyweight):实现接口,并且有相关的状态

        不共享具体轻量级类(UnsharedConcreteFlyweight):不被共享的具体轻量级类

        轻量级类工厂(FlyweightFactory):创建并且管理Flyweight对象,当客户端发出轻量级类请求时提供一个已创建或者未创建的对象

        客户端(Client) :只需要使用轻量级类工厂调用相应的轻量级类即可。

 实现思路:客户端调用轻量级类工厂,工厂去查找是否已经有轻量级类实例,如果有则直接返回给客户端,如果没有则根据条件创建相应的实例给客户端。

 类图:

 

应用场景:游戏中的衣服实对象有很多种,会背穿在很多人的身上。

分析:游戏中的衣服它穿在很多人的身上,如果为每个人身上的衣服设置一个实例,那么对服务器的压力将不言而喻,这时如果在衣服内部设置很多种状态属性,在客户端调用的时候,使用轻量级类工厂来创建选择即可。

        下面我们在控制台程序去演示一下如何使用Flyweight Pattern:

        一、抽象轻量级类(Flyweight)

    //抽象轻量级类(Flyweight)
abstract class Clothes
{
public string Name { get; set; }
public int Defense { get; set; }
public abstract void GetDefense();
}

        二、具体轻量级类(ConcreteFlyweight)

    //具体轻量级类(ConcreteFlyweight)
class LowClothes : Clothes
{
public LowClothes()
{
Name = "青铜圣衣";
Defense = 50;
}
public override void GetDefense()
{
Console.WriteLine(Name + "的防御是" + Defense);
}
}

//具体轻量级类(ConcreteFlyweight)
class MiddleClothes : Clothes
{
public MiddleClothes()
{
Name = "白银圣衣";
Defense = 80;
}
public override void GetDefense()
{
Console.WriteLine(Name + "的防御是" + Defense);
}
}

//具体轻量级类(ConcreteFlyweight)
class HighClothes : Clothes
{
public HighClothes()
{
Name = "黄金圣衣";
Defense = 100;
}
public override void GetDefense()
{
Console.WriteLine(Name + "的防御是" + Defense);
}
}

        三、轻量级类工厂(FlyweightFactory)

    //轻量级类工厂(FlyweightFactory)
class ClothesFactory
{
private Hashtable clothesHT = new Hashtable();
public Clothes GetClothes(string clothesName)
{
Clothes clothes = (Clothes)clothesHT[clothesName];
if (clothes == null)
{
switch (clothesName)
{
case "青铜圣衣": clothes = new LowClothes();
break;
case "白银圣衣": clothes = new MiddleClothes();
break;
case "黄金圣衣": clothes = new HighClothes();
break;
}
clothesHT.Add(clothesName, clothes);
}
return clothes;
}
}

        四、客户端(Client) 

    //客户端(Client)
class Program
{
static void Main(string[] args)
{
ClothesFactory fac = new ClothesFactory();
fac.GetClothes("黄金圣衣").GetDefense();
fac.GetClothes("白银圣衣").GetDefense();
fac.GetClothes("黄金圣衣").GetDefense();
fac.GetClothes("黄金圣衣").GetDefense();
fac.GetClothes("青铜圣衣").GetDefense();
fac.GetClothes("白银圣衣").GetDefense();
Console.ReadLine();
}
}

        如需源码请点击 FlyWeightPattern.zip 下载。

posted @ 2011-10-12 10:31  .NET架构  阅读(2549)  评论(4编辑  收藏  举报