比如在网页上显示多幅图片的时候,为了减轻服务器负担,不是每一幅都从服务器上Download,而是同样的图片只生成一次,然后在不同的地方显示,在实现上,一般用对象工厂的方式,具体是否创建对象由工厂判断决定。
这个例子用Flyweight设计模式实现如下:
/// Flyweight Design Pattern.
class MainApp
{
static void Main()
{
FlyweightFactory factory = new FlyweightFactory();
// 用对象工厂取得“山”的图片
Flyweight f1 = factory.GetFlyweight("山");
//在坐标1,2处显示该图片
f1.Display(1,2);
// 用对象工厂取得“水”的图片
Flyweight f2 = factory.GetFlyweight("水");
//在坐标1,3处显示该图片
f2.Display(1, 3);
// 用对象工厂取得“山”的图片 因为前边已经存在山的图片,对象工厂会直接返回已有图片而不是再创建。
Flyweight f3 = factory.GetFlyweight("山");
//在坐标1,4处显示该图片
f3.Display(1, 4);
// Wait for user
Console.ReadKey();
}
}
/// FlyweightFactory,如果某图片已经生成(flyweights表中存在),则不重复创建。
class FlyweightFactory
{
private Hashtable flyweights = new Hashtable();
// Constructor
public FlyweightFactory()
{
}
//根据图片的名字,取得图片对象。
public Flyweight GetFlyweight(string name)
{
//如果Hash表中不存在该图片则创建。
if (flyweights[name] == null)
{
flyweights.Add(name, new ImageFlyweight(name));
}
return ((Flyweight)flyweights[name]);
}
}
///图片类的抽象类
abstract class Flyweight
{
public abstract void Display(int x, int y);
}
//图片类,提供Display显示图片的方法。
class ImageFlyweight : Flyweight
{
string _name;
public ImageFlyweight(string name)
{
_name = name;
}
public override void Display(int x, int y)
{
Console.WriteLine(string.Format("坐标{0},{1}处显示 {2}", x, y, _name));
}
}
没有评论:
发表评论