[C ++ design mode] adapter Mode
In STL, the stack encapsulates the vector or double-end queue, and the stack operation interface is a typical adapter mode.
The adapter mode is used to convert an interface of a class to another interface that the customer wants.
Using the adapter mode has the following advantages:
This reduces the difficulty of implementing a function. You can package existing classes to use them;
This improves the quality of the project. Existing classes are generally tested. After using the adapter mode, you do not need to perform a full coverage test on the old classes;
In general, it improves efficiency and reduces costs.
Based on the combination and Inheritance of classes, the adapter mode is divided into Object Adapter mode and class adapter mode.
Since the class adapter and Object Adapter are available, how can we choose between them?
Class adapters have the following features:
Since the Adapter directly inherits from the Adaptee class, you can redefine the method of the Adaptee class in the Adapter class;
If an abstract method is added to Adaptee, the Adapter must be modified accordingly, resulting in high coupling;
If Adaptee has other sub-classes and you want to call methods of other sub-classes of Adaptee In the Adapter, you cannot use the class Adapter.
Object adapters have the following features:
Sometimes, you will find that it is not easy to construct an Adaptee object;
When Adaptee adds a new abstract method, the Adapter class does not need to make any adjustment, but can also perform the correct action;
You can use polymorphism to call the method of the Adaptee subclass in the Adapter class.
Because the Coupling Degree of the Object Adapter is relatively low, we recommend that you use the Object Adapter in many books. In our actual project, this is also the case. If we can use object combinations, we will not use multi-inheritance methods.
Implementation Code of class adapter:
// Targetsclass Target{public:virtual void Request(){cout<
Request();delete targetObj;targetObj = NULL;return 0;}
Code for Object Adapter mode:
class Target{public:Target(){}virtual ~Target(){}virtual void Request(){cout<
SpecificRequest();}private:Adaptee *m_Adaptee;};int main(int argc, char *argv[]){Target *targetObj = new Adapter();targetObj->Request();delete targetObj;targetObj = NULL;return 0;}