1. 程式人生 > 實用技巧 >第10節:1-9節複習總結【多測師_王sir】【軟體測試培訓】【www.duoceshi.cn】

第10節:1-9節複習總結【多測師_王sir】【軟體測試培訓】【www.duoceshi.cn】

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)
	{
		cout << "RectangleAdapter::Draw()" << endl;
		LegacyDraw();
	}
};

// 組合方式的Adapter
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 的理解,是本質, 上述理解,依然適用組合方式。
  只是重點1發生了變化, 介面卡需要獲得訪問老介面的能力,之前是通過繼承方式,現在是通過組合方式。

設計模式這種東西,看部落格僅僅是知道怎麼回事,如果需要熟練使用,最好是結合專案。

.