Home > Article > Backend Development > C++ design pattern brief introduction to flyweight pattern
Flyweight mode: Use sharing technology to effectively support a large number of fine-grained objects.
Four role classes:
Flyweight flyweight class: the super class or interface of all specific flyweight classes. Through this interface, Flyweight can accept and act on external states.
Flyweight Flyweight Factory Class: A Flyweight Factory used to create and manage Flyweight. When the user requests a Flyweight, the FlyweightFactory object provides a created instance or creates one (if it does not exist).
ConcreteFlyweight concrete flyweight class: inherit the Flyweight super class or implement the Flyweight interface, and add storage space for internal state.
UnSharedConcreteFlyweight Specific Flyweight subclasses that do not need to be shared refer to those Flyweight subclasses that do not need to be shared. Because Flyweight interface class sharing is possible, but sharing is not mandatory.
Pattern implementation:
[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]; } };
Client:
[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; }
Flyweight pattern benefits:
If an application uses a large number of objects, and a large number of These objects should be considered when they create a large storage overhead.
Most states of an object can use external state. If the external state of an object is deleted, many groups of objects can be replaced with relatively few shared objects. At this time, you can consider using the Flyweight pattern.
The above is the content of the C++ design pattern brief introduction to the flyweight pattern. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!