duck.h
1 #ifndef _DUCK_H_ 2 #define _DUCK_H_ 3 4 class DUCK { 5 public: 6 virtual void quack() = 0; 7 virtual void fly() = 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 class MALLARD_DUCK : public DUCK { 8 public: 9 void quack() { std::cout << "mallard duck quack" << std::endl; } 10 void fly() { std::cout << "mallard duck fly" << std::endl; } 11 }; 12 #endif
turkey.h
1 #ifndef _TURKEY_H_ 2 #define _TURKEY_H_ 3 4 #include <iostream> 5 6 class TURKEY { 7 public: 8 void gobble() { std::cout << "turkey gobble" << std::endl; } 9 void fly() { std::cout << "turkey fly" << std::endl; } 10 }; 11 12 #endif
turkey_adapter.h
1 #ifndef _TURKEY_ADAPTER_H_ 2 #define _TURKEY_ADAPTER_H_ 3 4 #include "turkey.h" 5 class TURKEY_ADAPTER : public DUCK{ 6 private: 7 TURKEY &turkey; 8 public: 9 TURKEY_ADAPTER( TURKEY &_turkey) : turkey(_turkey) {} 10 void quack() { turkey.gobble(); } 11 void fly() { 12 for ( int i = 0; i < 3; i++ ) { 13 turkey.fly(); 14 } 15 } 16 }; 17 #endif
main.cpp
1 #include "mallard_duck.h" 2 #include "turkey_adapter.h" 3 4 void test_duck( DUCK &p ) { 5 p.quack(); 6 p.fly(); 7 } 8 9 int main() { 10 MALLARD_DUCK mallard_duck; 11 test_duck( mallard_duck ); 12 13 TURKEY turkey; 14 TURKEY_ADAPTER turkey_adapter(turkey); 15 test_duck( turkey_adapter ); 16 }
时间: 2024-10-23 02:22:26