[Disclaimer: All Rights Reserved. You are welcome to reprint it. Do not use it for commercial purposes. Contact Email: feixiaoxing @ 163.com]
In our daily life, we are inseparable from various electronic tools. Any laptop, mobile phone, or MP4 cannot be charged. The charger is needed for charging. In fact, basically, the charger is a common adapter. What is an adapter? It is to program the AC voltage of 220 V and 50Hz 5 ~ 12 v dc voltage. The charger did this.
So how should we use C ++ to describe such a charging adapter?
[CPP] View plaincopyprint?
-
- ClassVoltage_12v
-
- {
-
- Public:
-
- Voltage_12v (){}
-
- Virtual~ Voltage_12v (){}
- Virtual VoidRequest (){}
-
- };
-
-
- ClassV220_to_v12
-
- {
-
- Public:
-
- V220_to_v12 (){}
-
- ~ V220_to_v12 (){}
-
- VoidVoltage_transform_process (){}
-
- };
-
- ClassAdapter:PublicVoltage_12v
-
- {
-
- V220_to_v12 * padaptee;
-
-
- Public:
-
- Adapter (){}
-
- ~ Adapter (){}
-
-
- VoidRequest ()
-
- {
- Padaptee-> voltage_transform_process ();
-
- }
-
- };
class voltage_12v <br/>{< br/> public: <br/> voltage_12 V () {}< br/> virtual ~ Voltage_12v () {}< br/> virtual void request () {}< br/> }; </P> <p> class v220_to_v12 <br/>{< br/> Public: <br/> v220_to_v12 () {}< br/> ~ V220_to_v12 () {}< br/> void voltage_transform_process () {}< br/>}; </P> <p> class adapter: public voltage_12v <br/>{< br/> v220_to_v12 * padaptee; </P> <p> Public: <br/> adapter () {}< br/> ~ Adapter () {}</P> <p> void request () <br/>{< br/> padaptee-> voltage_transform_process (); <br/>}< br/>};
Through the aboveCodeWe can understand it in this way. Voltage_12v indicates that our ultimate goal is to obtain a 12 v dc voltage. Of course, there are many ways to get 12 V. Using adapter conversion is only one of them. Adapter indicates the adapter, which cannot convert v to 12 V by itself. Therefore, you need to call the Conversion Function of v220_to_v12 class. Therefore, the process of getting 12 V using the adapter is actually the process of calling the v220_to_v12 function.
However, since our topic isC LanguageTo write the adapter mode, we need to achieve the initial goal. This is actually not difficult. The key step is to define the data structure of an adapter. Then all the adapter work is done by adaptee, which is so simple. I don't know if I have explained it?
[CPP] View plaincopyprint?
-
- TypdefStruct_ Adaptee
-
- {
-
- Void(* Real_process )(Struct_ Adaptee * padaptee );
- } Adaptee;
-
-
- Typedef Struct_ Adapter
-
- {
-
- Void* Padaptee;
-
- Void(* Transform_process )(Struct_ Adapter * padapter );
-
-
- } Adapter;