上篇做了object adapter 範例,這篇輪到class Adapter,其實我上網爬了一陣子文,發現大家基本上都只寫object adapter範例(?)。 class Adapter通常利用多重繼承,讓一個類別繼承多個類別,獲得多個類別的屬性,就可以被當成其他類別使用。因為Java沒辦法用多重繼承,所以今天用C++來寫~
假設我們是歐洲人到美國旅遊,那就會需要歐規轉美規的轉接頭,這邊就簡單實作一下:
#include <iostream>
using namespace std;
// European plug interface
class EuropeanPlug {
public:
virtual void plugInEuropeanSocket() = 0;
};
// European charger for your smartphone
class EuropeanCharger : public EuropeanPlug {
public:
void plugInEuropeanSocket() override {
cout << "Charging your smartphone with a European plug." << endl;
}
};
// US socket interface
class USSocket {
public:
virtual void plugInUSSocket() = 0;
};
// Adapter to make European plug work with US socket
class PlugAdapter : public USSocket {
private:
EuropeanPlug* europeanPlug;
public:
PlugAdapter(EuropeanPlug* plug) : europeanPlug(plug) {}
void plugInUSSocket() override {
cout << "Using an adapter to plug your European charger into a US socket." << endl;
europeanPlug -> plugInEuropeanSocket(); // Delegate to the European charger
}
};
int main() {
EuropeanPlug* europeanCharger = new EuropeanCharger();
USSocket* adapter = new PlugAdapter(europeanCharger);
// Now, you can plug your European charger into a US socket using the adapter.
adapter -> plugInUSSocket();
}
輸出: