享元模式:
运用共享技术,让一部分代码被多个类共享。
using System;
using System.Collections;
using System.Text;
namespace 设计模式
{
abstract class Flyweight
{
public abstract void Operation(string extrinsicState);
}
class ConcreteFlyWeight : Flyweight
{
private string name;
public ConcreteFlyWeight(string name) { this.name = name; }
public override void Operation(string extrinsicState)
{
Console.WriteLine("具体"+name+"Flyweight:" + extrinsicState);
}
}
class FlyweightFactory
{
private Hashtable flyweights = new Hashtable();
public Flyweight GetFlyweight(string key)
{
if (!flyweights.ContainsKey(key))
flyweights.Add(key, new ConcreteFlyWeight(key));
return ((Flyweight)flyweights[key]);
}
}
class Costume
{
//客户端程序
static void Main(string[] args)
{
FlyweightFactory f = new FlyweightFactory();
Flyweight f1 = f.GetFlyweight("小李");
f1.Operation("lalala");
Flyweight f2 = f.GetFlyweight("小李");
f2.Operation("hahaha");
Flyweight f3 = f.GetFlyweight("小lin");
f3.Operation("hehehe");
Flyweight f4 = f.GetFlyweight("小chen");
f4.Operation("hihihi");
}
}
}
结果
具体小李Flyweight:lalala
具体小李Flyweight:hahaha
具体小linFlyweight:hehehe
具体小chenFlyweight:hihihi