Mark As Completed Discussion

Structural Design Patterns

Structural design patterns focus on establishing relationships between objects, making it easier to design a flexible and reusable system. These patterns help in defining how different parts of a system can work together to form larger structures without making the system complex or unmanageable.

Adapter Pattern

The Adapter pattern allows objects with incompatible interfaces to work together by providing a common interface. It acts as a bridge between the old and the new, allowing the components to collaborate without modifying their original code.

In the code example below, we have an Adapter interface that defines the common interface for different types of adapters. The ConcreteAdapter class implements this interface and internally uses the ConcreteAdaptee class to fulfill the required behavior. The ConcreteAdaptee class has a specific method called specificRequest(), which is adapted by the ConcreteAdapter class.

TEXT/X-C++SRC
1#include <iostream>
2
3using namespace std;
4
5// Adapter interface
6
7class Adapter {
8 public:
9  virtual void request() const = 0;
10};
11
12// ConcreteAdaptee class
13
14class ConcreteAdaptee {
15 public:
16  void specificRequest() const {
17    cout << "Specific request" << endl;
18  }
19};
20
21// ConcreteAdapter class
22
23class ConcreteAdapter : public Adapter {
24 private:
25  ConcreteAdaptee *adaptee;
26
27 public:
28  ConcreteAdapter(ConcreteAdaptee *adaptee) : adaptee(adaptee) {}
29
30  void request() const override {
31    adaptee->specificRequest();
32  }
33};
34
35int main() {
36  // Create an instance of ConcreteAdaptee
37  ConcreteAdaptee *adaptee = new ConcreteAdaptee();
38
39  // Create an instance of ConcreteAdapter
40  Adapter *adapter = new ConcreteAdapter(adaptee);
41
42  // Call the request method on the adapter
43  adapter->request();
44
45  return 0;
46}

By using the Adapter pattern, we can easily integrate legacy code or third-party libraries into new systems while maintaining a consistent and unified interface.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment