随笔-91  评论-137  文章-0  trackbacks-0

适配器模式

前序

姚明,大家都认识吧。在他刚去NBA的时候,什么都听不懂,必须在旁边配个翻译,否则就无法听懂教练在说什么。这也正符合了设计模式中的一种模式:适配器模式。

适配器模式

将一个类的接口转换成客户希望的另外一个接口。适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

实现方式(UML类图)


实现代码

#include <stdio.h>

 

// 球员

class Player

{

public:

       Player(char* _name) : name(_name){}

      

       virtual void Attack()=0;

       virtual void Defense()=0;

 

       char* name;

};

 

// 前锋

class Forwards : public Player

{

public:

       Forwards(char* name) : Player(name){}

      

       virtual void Attack()

       {

              printf("前锋 %s 进攻\n", name);

       }

      

       virtual void Defense()

       {

              printf("前锋 %s 防守\n", name);

       }

};

 

// 中锋

class Center : public Player

{

public:

       Center(char* name) : Player(name){}

      

       virtual void Attack()

       {

              printf("中锋 %s 进攻\n", name);

       }

      

       virtual void Defense()

       {

              printf("中锋 %s 防守\n", name);

       }

};

 

// 后卫

class Guards : public Player

{

public:

       Guards(char* name) : Player(name){}

      

       virtual void Attack()

       {

              printf("后卫 %s 进攻\n", name);

       }

      

       virtual void Defense()

       {

              printf("后卫 %s 防守\n", name);

       }

};

 

// 外籍中锋

class ForeignCenter

{

public:

       void Attack()

       {

              printf("外籍中锋 %s 进攻\n", name);

       }

      

       void Defense()

       {

              printf("外籍中锋 %s 防守\n", name);

       }

      

       char* name;

};

 

// 翻译者

class Translator : public Player

{

public:

       Translator(char* name) : Player(name)

       {

              wjzf.name = name;

       }

      

       virtual void Attack()

       {

              wjzf.Attack();

       }

      

       virtual void Defense()

       {

              wjzf.Defense();

       }

protected:

       ForeignCenter wjzf;

};

 

int main()

{

       Player* b = new Forwards("巴蒂尔");

       b->Attack();

      

       Player* m = new Guards("麦克格雷迪");

       m->Attack();

      

       Player* ym = new Translator("姚明");

       ym->Attack();

       ym->Defense();

      

       delete b;

       delete m;

       delete ym;

      

       return 0;

}

运行结果



所有文件打包下载

posted on 2011-08-14 15:27 lwch 阅读(2672) 评论(4)  编辑 收藏 引用 所属分类: 设计模式

评论:
# re: 适配器模式 2011-08-14 20:19 | func
配图搞错了吧。  回复  更多评论
  
# re: 适配器模式 2011-08-14 21:48 | 饭中淹
配图。。。  回复  更多评论
  
# re: 适配器模式 2011-08-14 22:58 | lwch
@func
已经修正  回复  更多评论
  
# re: 适配器模式 2013-02-05 11:28 | hsc
写得不错, 学以致用, 向你学习  回复  更多评论
  

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理