码迷,mamicode.com
首页 > 编程语言 > 详细

Headfirst设计模式的C++实现——适配器(Adapter)

时间:2016-04-29 23:48:42      阅读:368      评论:0      收藏:0      [点我收藏+]

标签:

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 }

 

Headfirst设计模式的C++实现——适配器(Adapter)

标签:

原文地址:http://www.cnblogs.com/ren-yu/p/5447845.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!