Adapter Design Pattern (C++)
The Adapter pattern acts as a bridge between two incompatible interfaces. It allows two classes with incompatible interfaces to work together by converting the interface of one class into an interface that the other expects.
The Adapter pattern can be seen as a wrapper that modifies an existing class’s interface without altering its underlying code.
Core Roles
- Target – The interface the client expects.
- Adaptee – The existing interface that must be adapted.
- Adapter – Converts the Adaptee interface into the Target interface.
Code Example
Target.h
class Target
{
public:
virtual void Request() = 0;
virtual ~Target() = default;
};
Adaptee.h
class Adaptee
{
public:
void SpecificRequest();
};
Adaptee.cpp
#include "Adaptee.h"
#include <iostream>
void Adaptee::SpecificRequest()
{
std::cout << "[Adaptee] SpecificRequest\n";
}
Adapter.h
#include "Target.h"
#include "Adaptee.h"
class Adapter : public Target, public Adaptee
{
Adaptee m_Adaptee;
public:
void Request() override;
};
Adapter.cpp
#include "Adapter.h"
#include <iostream>
void Adapter::Request()
{
std::cout << "[Adapter] Calling SpecificRequest\n";
SpecificRequest();
}
main.cpp
#include "Target.h"
#include "Adapter.h"
void Client(Target* pTarget)
{
pTarget->Request();
}
int main()
{
Adapter adapter;
Client(&adapter);
}
Program Output
[Adapter] Calling SpecificRequest
[Adaptee] SpecificRequest
S.W.O.T. Analysis (C++)
Strengths
- Enables compatibility between incompatible interfaces
- Promotes reuse of legacy and third-party code
- Decouples client code from implementation details
Weaknesses
- Introduces additional abstraction layers
- Slight runtime overhead
- Can overcomplicate small systems
Opportunities
- Modernizing legacy C++ systems
- Wrapping third-party APIs
- Bridging C++ with other languages
Threats
- Clients bypassing the adapter
- Design clutter from excessive adapters
- Simpler refactoring alternatives

No comments:
Post a Comment