适配器模式

 

1. 先贴源码

#include <string>
#include<iostream>
using namespace std;
 
class LegacyRectangle
{
public:
    LegacyRectangle(double x1, double y1, double x2, double y2)
    {
        _x1 = x1;
        _y1 = y1;
        _x2 = x2;
        _y2 = y2;
    }
 
    void LegacyDraw()
    {
        cout << "LegacyRectangle:: LegacyDraw()" << _x1 << " " << _y1 << " " << _x2 << " " << _y2 << endl;
    }
 
private:
    double _x1;
    double _y1;
    double _x2;
    double _y2;
};
 
class Rectangle
{
public:
    virtual void Draw(string str) = 0;
};
 
// 第一种实现适配器的方式:  使用多重继承
class RectangleAdapter: public Rectangle, public LegacyRectangle
{
public:
    RectangleAdapter(double x, double y, double w, double h) :
        LegacyRectangle(x, y, x + w, y + h)
    {
        cout << "RectangleAdapter(int x, int y, int w, int h)" << endl;
    }
 
    virtual void Draw(string str)
    {
        //在新接口内,不仅可以调用原有的老的绘图接口  
          LegacyDraw();
         //还可以新增提示用户语句,例如实现语音播报:系统即将绘图!(此处以cout输出到终端代替)
    cout << "RectangleAdapter::Draw()" << endl;
  }
 };
 
// 第二种实现适配器的方式:使用组合方式
class RectangleAdapter2 :public Rectangle
{
private:
    LegacyRectangle _lRect;
public:
    RectangleAdapter2(double x, double y, double w, double h) : _lRect(x, y, x + w, y + h)
    {
        cout << "RectangleAdapter2(int x, int y, int w, int h)" << endl;
    }
    virtual void Draw(string str)
    {
        cout << "RectangleAdapter2::Draw()" << endl; _lRect.LegacyDraw();
    }
};
 
int main()
{
    double x = 20.0, y = 50.0, w = 300.0, h = 200.0;
    RectangleAdapter ra(x, y, w, h);
    Rectangle* pR = &ra;
    pR->Draw("Testing Adapter");
     
    cout << endl;
     
    RectangleAdapter2 ra2(x, y, w, h);
    Rectangle* pR2 = &ra2;
    pR2->Draw("Testing2 Adapter");
    return 0;
}

  

适配器模式个人理解:

有两种实现方式:1. 多重继承方式 ;  2. 组合方式


1. 多重继承方式
  适配器类可以继承于原接口API类和新接口API类,
  适配器类构造的时候负责初始化原有接口API类的对象模型,
  适配器类需要实现新接口API类内的纯虚函数,并在其中调用原有接口API。。

  最后通过新接口API类内的纯需函数接口,以多态的方式,来达到调用适配器内的原有接口API。

  感悟: 适配器需要获得访问老接口的能力, --重点1
  适配器对内实现了老->新接口API的转换, --重点2
  对外,由于其虚继承于新接口类,所以又可以通过新接口类被外部访问。 --重点3

2. 组合方式
  对多重继承方式内的重点1 、 重点2 、重点3的理解,是本质, 上述理解,依然适用组合方式。
  只是重点1发生了变化, 适配器需要获得访问老接口的能力,之前是通过继承方式,现在是通过组合方式。

 

设计模式这种东西,看博客仅仅是知道怎么回事,如果需要熟练使用,最好是结合项目。

 

 

 

 

.

posted @ 2020-09-03 15:04  一匹夫  阅读(201)  评论(0编辑  收藏  举报