首頁  >  文章  >  後端開發  >  C++設計模式淺識享元模式

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

黄舟
黄舟原創
2017-01-17 13:27:001372瀏覽

享元模式(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]//Client
int 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++設計模式淺識享元模式的內容,更多相關內容請關注PHP中文網(www.php.cn)!


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn