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發生了變化, 擴充卡需要獲得通路老接口的能力,之前是通過繼承方式,現在是通過組合方式。
設計模式這種東西,看部落格僅僅是知道怎麼回事,如果需要熟練使用,最好是結合項目。
.
/************* 社會的有色眼光是:博士生、研究所學生、大學生、工廠中的房間勞工; 重點大學高材生、普通院校、二流院校、野雞大學; 年薪百萬、五十萬、五萬; 這些都隻是帽子,可以失敗千百次,但我和社會都覺得,人隻要成功一次,就能換一頂帽子,隻是社會看不見你之前的失敗的帽子。 當然,換帽子決不是最終目的,走好自己的路就行。 杭州.大話西遊 *******/