享元模式(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)!