当前位置:   article > 正文

C++设计模式-适配器模式_c++ 适配器模式

c++ 适配器模式

目录

 

 

基本概念

代码与实例


 

基本概念

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

 

当系统的数据和行为都正常,但接口不负荷时,可以考虑使用适配器,目的是使控制范围之外的一个原有对象与某个接口匹配。适配器模式主要应用于希望复用一些现存的类,但是接口又与复用的环境要求不一致的情况。

 

什么时候使用适配器模式:

          1. 使用一个已经存在的类,但如果它的接口,也就是它的方法和你的要求不同时使用。

          2. 客户代码要求统一调用同一接口。

          3. 双方都不太容易修改的时候再使用适配器模式;

 

本人在此总结下,这个就像套子一样,比如在某个结构里面,有了很多设计模式和功能,但我这个系统,又可以作为另外一个大系统的小功能,而那个大系统又有某种规范,此时给自己的系统带一个套子,使得他能顺利的进入那个大系统,按F进入坦克。哈哈哈!

 

代码与实例

结构如下所示(此图来源于大话设计模式):

程序运行截图如下:

源码如下:

Head.h

  1. #ifndef HEAD_H
  2. #define HEAD_H
  3. //客户期待的接口,目标可以是具体的或者抽象的类,也可以是接口
  4. class Target{
  5. public:
  6. virtual void request();
  7. virtual ~Target();
  8. };
  9. //需要适配的类
  10. class Adaptee{
  11. public:
  12. void specificRequest();
  13. };
  14. //通过内部包装一个Adaptee对象,把源接口转换为目标接口
  15. class Adapter : public Target{
  16. public:
  17. void request();
  18. ~Adapter();
  19. Adapter();
  20. private:
  21. Adaptee *adaptee;
  22. };
  23. #endif HEAD_H

Head.cpp

  1. #include "Head.h"
  2. #include <iostream>
  3. #include <string>
  4. using namespace std;
  5. void Target::request()
  6. {
  7. cout << "普通请求!" << endl;
  8. }
  9. Target::~Target()
  10. {
  11. cout << "Target::~Target() called!" << endl;
  12. }
  13. void Adaptee::specificRequest()
  14. {
  15. cout << "特殊请求!" << endl;
  16. }
  17. void Adapter::request()
  18. {
  19. adaptee->specificRequest();
  20. }
  21. Adapter::~Adapter()
  22. {
  23. cout << "Adapter::~Adapter() called!" << endl;
  24. }
  25. Adapter::Adapter()
  26. {
  27. //建立一个私有的Adaptee对象
  28. adaptee = new Adaptee;
  29. }

Main.cpp

  1. #include "Head.h"
  2. #include <iostream>
  3. #include <string>
  4. using namespace std;
  5. int main(int *argc, int *argv[]){
  6. Target *target = new Adapter;
  7. target->request();
  8. delete target;
  9. getchar();
  10. return 0;
  11. }

 

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
  

闽ICP备14008679号