Adapter Pattern 是一種結構型設計模式,旨在允許兩個不相容的接口能夠協同工作
組成:
流程: Client <-> Target (Interface) <-> Adapter <-> Adaptee
分析:
應用場景:
// 目標接口 (Target)
class Target {
public:
virtual void request() = 0;
};
// 待適配的接口 (Adaptee)
class Adaptee {
public:
void specificRequest() {
// 這是原本的方法,與目標接口不相容
cout << "Called Specific Request!" << endl;
}
};
// 適配器 (Adapter)
class Adapter : public Target {
private:
Adaptee* adaptee; // 持有一個待適配的接口的實例
public:
Adapter(Adaptee* a) : adaptee(a) {}
// 實作目標接口的請求方法
void request() override {
// 轉換呼叫為待適配的接口的呼叫
adaptee->specificRequest();
}
};
int main() {
// 創建被適配者
Adaptee* adaptee = new Adaptee();
// 透過適配器使其與目標接口相容
Target* target = new Adapter(adaptee);
// 客戶端僅與目標接口互動
target->request(); // 輸出: Called Specific Request!
}
class Target {
virtual void targetRequest() = 0
}
class Adaptee {
void specificRequest() {
// specific behavior
}
}
class TwoWayAdapter : public Target {
private:
Target* targetInstance;
Adaptee* adapteeInstance;
public:
TwoWayAdapter(Target* t, Adaptee* a): targetInstance(t), adapteeInstance(a) {}
// Target 向 Adaptee 溝通
void targetRequest() override {
adapteeInstance->specificRequest();
}
// Adaptee 向 Target 溝通
void adaptSpecificRequest() {
targetInstance->targetRequest();
}
}
// 主程式範例:
Target* concreteTarget = new ConcreteTarget();
Adaptee* adaptee = new Adaptee();
TwoWayAdapter* adapter = new TwoWayAdapter(concreteTarget, adaptee);
adapter->targetRequest(); // Calls Adaptee's specificRequest method
adapter->adaptSpecificRequest(); // Calls ConcreteTarget's targetRequest method
[1]. https://www.geeksforgeeks.org/adapter-pattern/