public ConcreateCompany(string name)
: base(name)
{ }
public override void Add(Company c)
{
children.Add(c);
}
public override void Remove(Company c)
{
children.Remove(c);
}
public override void Display(int depth)
{
Console.WriteLine(new string('-',depth )+name );
foreach (Company component in children)
{
component.Display(depth+2);
}
}
public override void LineOfDuty()
{
foreach (Company component in children)
{
component.LineOfDuty();
}
}
}
class HRDepartment : Company //树枝节点——人力资源部和财务部
{
public HRDepartment(string name)
: base(name)
{ }
public override void Add(Company c)
{ }
public override void Remove(Company c)
{
}
public override void Display(int depth)
{
Console.WriteLine(new string('-',depth )+name );
}
public override void LineOfDuty()
{
Console.WriteLine("{0}员工招聘培训管理",name );
}
}
class FinanceDepartment : Company //财务部
{
public FinanceDepartment(string name)
: base(name)
{ }
public override void Add(Company c)
{
}
public override void Remove(Company c)
{
}
public override void Display(int depth)
{
Console.WriteLine(new string('-',depth )+name);
}
public override void LineOfDuty()
{
Console.WriteLine("{0}公司财务收支管理",name );
}
}
}
10. 享元模式
运用共享技术有效地支持大量细粒度的对象。如果一个应用使用了大量的对象,而大量的这些对象造成很大的存储开销应该考虑使用享元模式。享元模式可以避免大量非常相似类的开销,如果发现一些实例除了几个参数外基本相同,可以大大减少需要实例化的类的数量,,把参数移到类实例的外面,方法调用是传递进去。(比如在一个汽车4S店,通过id可以查到汽车的信息,第一次查BMW 730会返回数据库宝马730的配置信息,第二次查得时候先从上次查得缓存中找,没有再找数据库,其实就是缓存的意思)
UML图:

代码:
view plaincopy to clipboardprint using System.Collections; //引用哈希表
namespace 享元模型
{
class Class1
{
static void Main(string[] args)
{
int extrinsicstate = 22;
FlyweightFactory f = new FlyweightFactory();
Flyweight fx = f.GetFlyweight("X");
fx.Operation(--extrinsicstate );
Flyweight fy = f.GetFlyweight("Y");
fy.Operation(--extrinsicstate );
Flyweight fz = f.GetFlyweight("Z");
fz.Operation(--extrinsicstate);
Flyweight uf = new UnsharedConcreteFlyweight();
uf.Operation(--extrinsicstate );
Console.Read();
}
}
abstract class Flyweight
{
//具体类和享元类的接口
public abstract void Operation(int extrinsicstate);
}
class ConcreteFlyweight : Flyweight
{
public override void Operation(int extrinsicstate)
{
Console.WriteLine("具体Flyweight:"+extrinsicstate );
}
}
class UnsharedConcreteFlyweight : Flyweight
{
public override void Operation(int extrinsicstate)
{
Console.WriteLine("不共享的具体Flyweight:" + extrinsicstate);
}
}
class FlyweightFactory //享元工厂
{
private H