Design pattern, is the crystallization of the wisdom of software design, but also every developer should learn.
Adapter mode: The interface of one class is converted into another interface that the customer wants, so that those classes that cannot work together because of incompatible interfaces can work together.
The adapter pattern can be divided into class adaptation and object adaptation. In terms of the actual situation in the development, the object adaptation mode is relatively more, the following notes in the adapter mode refers to the object adapter mode.
We develop with a variety of protocols, such as UDP, TCP, HTTP, etc., a system is generally a lot of modules, such as radio, there are tuner, Webapp, Bt, Power, HVAC and other modules, if some modules use different protocols, Is it possible for us to encapsulate the interface of all the protocols in a class, and then define a private member variable of the Protocol class in each module to invoke the non-Pass protocol interface, which does not implement a simple adapter mode. Language is too weak, let's look at UML class diagram bar.
To take a look at the code again, it may be clear:
#include <iostream>using namespacestd;classProtocolforest//Protocol Forest{ Public: voidTcpprotocol () {cout<<"Protocolforest::tcpprotocol ()"<<Endl; } voidUdpprotocol () {cout<<"Protocolforest::udpprotocol ()"<<Endl; } voidHttpprotocol () {cout<<"Protocolforest::httpprotocol ()"<<Endl; }};classBasemodule//base class{ Public: Virtual voidConnectionvoid) =0;};classTuner: PublicBasemodule//Tuner Module{Private: Protocolforest m_protocol; Public: Virtual voidConnectionvoid) {m_protocol.tcpprotocol (); cout<<"tuner::connection ()"<<Endl; }};classPower: PublicBasemodule//Power Module{Private: Protocolforest m_protocol; Public: Virtual voidConnectionvoid) {m_protocol.udpprotocol (); cout<<"power::connection ()"<<Endl; }};classWebapp: PublicBasemodule//WebApp Module{Private: Protocolforest m_protocol; Public: Virtual voidConnectionvoid) {m_protocol.udpprotocol (); cout<<"webapp::connection ()"<<Endl; }};intMainintargcChar**argv) {Basemodule* Modulea =NewWebapp (); Modulea-connection (); Modulea=NewTuner (); Modulea-connection (); DeleteModulea; return 0;}
The output is as follows:
Adapter mode (c + + implementation)