設計模式理解(十)結構型——享元(Flyweight)

最後一個結構型,享元。沒有太多的項目經驗,對這種模式只有一種概念上的理解,就是爲了節約內存等資源,把可重用的東西只申請一次,而後到處調用,同時用Hash進行管理。設計模式

    直接上圖:ide

 

代碼:spa

/*********  大話設計模式上的代碼 ************/

abstract class Flyweight{
    public abstract void Operation(int extrinsicstate); 
}

class ConcreteFlyweight : Flyweight{
    public override void Operation(int extrinsicstate){
        Console.WriteLine("具體Flyweight : " + extrinsicstate);
    }
}

class UnshareConcreteFlyweight : 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());
    }
    public Flyweight GetFlyweight(string key){
        return ((Flyweight)flyweights[key]);
    }
}
相關文章
相關標籤/搜索