Skip to content

Adapter Pattern

The adapter design pattern applies to any context where we effectively want to modify an existing class so that its methods match those a related, but different, class or interface.

One general way to apply the adapter pattern is to define a new class in such a way that it contains an instance of the existing class as a hidden field, and then to implement each method of the new class using methods of this hidden instance variable.

By applying the adapter pattern in this way, we have created a new class that performs some of the same functions as an existing class, but repacked in a more convenient way.

An example is to implement an Array based Stack using a Python list - with a simple example shown below.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Empty(Exception):
    """Error attempting to access an element from an empty container."""
    pass

class ArrayStack:
    """LIFO stack implementation using Python list as underlying storage"""

    def __init__(self):
        self._data = []

    def __len__(self):
        return len(self._data)

    def is_empty(self):
        return len(self._data) == 0

    def push(self, e):
        self._data.append(e)

    def top(self):
        if self.is_empty():
            raise Empty('Stack is Empty')
        return self._data[-1]

    def pop(self):
        if self.is_empty():
            raise Empty('Stack is Empty')
        return self._data.pop()