Adapter mode (Adapter): Transforms the interface of one class into another interface that the customer wants. Make the original interface incompatible and not work in one of those classes that can work together.
Usage Scenario: When the data and behavior of the system are correct, but the interface is not the same, we can consider using the adapter mode to match the interface. The main application is in the hope of reusing some existing classes, but the interface and multiplexing environment should not be used at the same time.
#ifndef adapter_h#define adaptte_h#include<iostream> #include <string>using namespace Std;class Player{ protected:string name;public:virtual void Attack () =0;virtual void Defense () = 0;}; Class forwards:p ublic player{public:forwards (string n) {name = n;} void Attack () {cout << "forward" << name << "offense." \ n ";} void Defense () {cout << "forward" << name << "defensive." \ n ";}}; Class Guards:p ublic player{public:guards (string n) {name = n;} void Attack () {cout << "defender" << name << "offense. \ n ";} void Defense () {cout << "defender" << name << "defensive." \ n ";}}; Class Foreigncenter:p ublic player{friend class translator;//declare Translator as a friend class, professional it can access the information inside Foreigncenter, That is, the translator can communicate with foreign players public:foreigncenter () {}foreigncenter (string n) {name = n;} private://statement as private means that the foreign center cannot understand the intentions of the coach attacking and defending. void Attack () {cout << "center" << name << "offense." \ n ";} void Defense () {cout << "center" << name << "defensive." \ n ";}}; Class Translator:p ublic player{foreigncenterFcenter;public:translator (string n) {fcenter.name=n;} void Attack () {fcenter.attack ();} void Defense () {fcenter.defense ();}}; #endif
#include "Adapter.h" int main () {Guards MC ("T-mac"); MC. Attack (); MC. Defense (); Forwards Bt ("Battier"); Bt.defense (); Bt.attack (); Translator Meimei ("Yao Ming")//Statement Meimei is Yao Ming's translation, when Meimei response to attack, is Meimei told Yao to attack Meimei.attack (); Meimei.defense (); return 0;}
Design pattern C + + implementation 13: Adapter mode