首页 > 代码库 > 享元模式
享元模式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Collections;
/*
享元模式
* (共享单元)
* 有太多的相同类型对象时,可以选用这个模式
* 减少存储开销
*
*
*/
namespace App_MYCS.HDL_SJMS.HYMS
{
class my_HYMS
{
public void Dy()
{
int i = 22;
FlyweightFactory f = new FlyweightFactory();
Flyweight fx = f.GetFlyweight("x");
fx.Operation(--i);
Flyweight fy = f.GetFlyweight("y");
fx.Operation(--i);
Flyweight fz = f.GetFlyweight("z");
fx.Operation(--i);
Flyweight fu = new UnsharedConcreteFlyweight();
fu.Operation(--i);
}
}
//抽像享元(抽像共享)
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 Hashtable flyweights = new Hashtable();
public FlyweightFactory()
{
//初始化就实例化共享单元集合的所有对象
flyweights.Add("X", new ConcreteFlyweight());
flyweights.Add("Y", new ConcreteFlyweight());
flyweights.Add("Z", new ConcreteFlyweight());
}
//通过标识获取共享单元
public Flyweight GetFlyweight(string key)
{
return (Flyweight)flyweights[key];
}
}
}
享元模式