C++設計模式淺識享元模式

來源:互聯網
上載者:User
享元模式(Flyweight):運用共用技術有效地支援大量細粒度的對象。

四個角色類:

Flyweight享元類:所有具體享元類的超類或介面,通過這個介面,Flyweight可以接受並作用於外部狀態。

Flyweight享元工廠類:一個享元工廠,用來建立並管理Flyweight,當使用者請求一個Flyweight時,FlyweightFactory對象提供一個已建立的執行個體或者建立一個(如果不存在的話)。

ConcreteFlyweight具體享元類:繼承Flyweight超類或實現Flyweight介面,並為內部狀態增加儲存空間。

UnSharedConcreteFlyweight不需共用的具體Flyweight子類、指那些不需要共用的Flyweight子類。因為Flyweight介面類共用成為可能,但並不強制共用。

模式實現:

[code]//享元類class Flyweight{public:    virtual void Operation(int extrinsicState){}};//具體享元類class ConcreteFlyweight: public Flyweight{public:    virtual void Operation(int extrinsicState)override{        std::cout << "ConcreteFlyweight: " << extrinsicState << std::endl;    }};//不需共用的Flyweight子類class UnSharedConcreteFlyweight: public Flyweight{public:    virtual void Operation(int extrinsicState){        std::cout << "UnSharedConcreteFlyweight: " << extrinsicState << std::endl;    }};//享元工廠,用來建立並管理Flyweight對象class FlyweightFactory{private:    std::map<std::string, Flyweight*> flyweights;public:    FlyweightFactory(){        flyweights["X"] = new ConcreteFlyweight;        flyweights["Y"] = new ConcreteFlyweight;        flyweights["Z"] = new ConcreteFlyweight;    }    Flyweight* GetFlyweight(std::string key){        return (Flyweight*)flyweights[key];    }};

用戶端:

[code]//Clientint main(){    //外部狀態    int extrinsicState = 22;    //工廠    FlyweightFactory *f = new FlyweightFactory;    Flyweight* fx = f->GetFlyweight("X");    fx->Operation(--extrinsicState);  //Output: ConcreteFlyweight: 21    Flyweight* fy = f->GetFlyweight("Y");    fy->Operation(--extrinsicState);  //Output: ConcreteFlyweight: 20    Flyweight* fz = f->GetFlyweight("Z");    fz->Operation(--extrinsicState);  //Output: ConcreteFlyweight: 19    Flyweight *uf = new UnSharedConcreteFlyweight;  //Output: UnSharedConcreteFlyweight: 18    uf->Operation(--extrinsicState);    return 0;}

享元模式好處:

如果一個應用程式使用了大量的對象,而大量的這些對象造成了很大的儲存開銷時就應該考慮使用。

對象的大多數狀態可以使用外部狀態,如果刪除對象的外部狀態,那麼可以用相對較少的共用對象取代很多組對象,此時可以考慮使用享元模式。

以上就是C++設計模式淺識享元模式的內容,更多相關內容請關注topic.alibabacloud.com(www.php.cn)!


  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.