效果:
类图:
代码:
1 #include<iostream> 2 using namespace std; 3 4 //抽象类AbstractDog 5 class AbstractDog { 6 public: 7 virtual void dog_looks() = 0; 8 virtual void bark() = 0; 9 }; 10 11 //抽象类AbstractCat 12 class AbstractCat { 13 public: 14 virtual void cat_looks() = 0; 15 virtual void grab() = 0; 16 }; 17 18 //Adapter类Dog 19 class Dog { 20 public: 21 void dog_looks() { 22 std::cout << "我是一只狗!" << std::endl; 23 } 24 void bark() { 25 std::cout << "我是狗,我会狗吠哦!" << std::endl; 26 } 27 }; 28 29 //Adapter类Cat 30 class Cat { 31 public: 32 void cat_looks() { 33 std::cout << "我是一只猫!" << std::endl; 34 } 35 void grab() { 36 std::cout << "我是猫,我会抓老鼠哦!" << std::endl; 37 } 38 }; 39 40 //Adapter类DogAdapter 41 class DogAdapter :public AbstractCat, private Dog { 42 public: 43 void cat_looks() { 44 std::cout << "猫模仿狗:" << std::endl; 45 Dog::dog_looks(); 46 } 47 void grab() { 48 std::cout << "猫模仿狗:" << std::endl; 49 Dog::bark(); 50 } 51 }; 52 53 //Adapter类CatAdapter 54 class CatAdapter :public AbstractDog, private Cat { 55 public: 56 void dog_looks() { 57 std::cout << "狗模仿猫:" << std::endl; 58 Cat::cat_looks(); 59 } 60 void bark() { 61 std::cout << "狗模仿猫:" << std::endl; 62 Cat::grab(); 63 } 64 }; 65 66 class Client { 67 public: 68 void client() { 69 DogAdapter* cat = new DogAdapter(); 70 cat->cat_looks(); 71 cat->grab(); 72 73 CatAdapter* dog = new CatAdapter(); 74 dog->dog_looks(); 75 dog->bark(); 76 } 77 }; 78 79 //Client 80 int main() { 81 Client client; 82 client.client(); 83 return 0; 84 85 }
参考链接:https://blog.csdn.net/janeqi1987/article/details/103945540