Duck.h
1 #ifndef _duck_h_2 #define_duck_h_3 4 classDUCK {5 Public:6 Virtual voidQuack () =0;7 Virtual voidFly () =0;8 };9 #endif
Mallard_duck.h
1 #ifndef _mallard_duck_h_2 #define_mallard_duck_h_3 4#include"duck.h"5#include <iostream>6 7 classMallard_duck: PublicDUCK {8 Public:9 voidQuack () {std::cout <<"Mallard Duck Quack"<<Std::endl;}Ten voidFly () {std::cout <<"Mallard Duck Fly"<<Std::endl;} One }; A #endif
Turkey.h
1 #ifndef _turkey_h_2 #define_turkey_h_3 4#include <iostream>5 6 classTURKEY {7 Public:8 voidGobble () {std::cout <<"Turkey Gobble"<<Std::endl;}9 voidFly () {std::cout <<"Turkey Fly"<<Std::endl;}Ten }; One A #endif
Turkey_adapter.h
1 #ifndef _turkey_adapter_h_2 #define_turkey_adapter_h_3 4#include"Turkey.h"5 classTurkey_adapter: Publicduck{6 Private:7TURKEY &Turkey;8 Public:9Turkey_adapter (TURKEY &_turkey): Turkey (_turkey) {}Ten voidQuack () {turkey.gobble ();} One voidFly () { A for(inti =0; I <3; i++ ) { - turkey.fly (); - } the } - }; - #endif
Main.cpp
1#include"mallard_duck.h"2#include"Turkey_adapter.h"3 4 voidTest_duck (Duck &p) {5 P.quack ();6 p.fly ();7 }8 9 intMain () {Ten Mallard_duck Mallard_duck; One Test_duck (mallard_duck); A - TURKEY TURKEY; - turkey_adapter Turkey_adapter (TURKEY); the Test_duck (turkey_adapter); -}
Headfirst design mode C + + implementation--Adapter (Adapter)