The purpose is to present a client code with abstract api, rather than a number of different apis with similar goals
Example
- AC Adapters
- Pipe Adapter
- US - India Power Sockets
Also Known As the Wrapper Pattern
Favour Composition over Inheritance always!
- It leads to flatter class structure
- Easy to understand, Debug and Maintain
from abc import ABCMeta, abstractproperty
class Customer():
def __init__(self, name, address):
self._name = name
self._address = address
@property
def name(self):
return self._name
@property
def address(self):
return self._address
MOCK_CUSTOMERS = (
Customer('Pizza Love', '33 Peperoni Lane'),
Customer('Happy and Green', '25 Kale St.'),
Customer('Sweet Tooth', '42 Chocolate Ave.')
)
class Vendor():
def __init__(self, name, number, street):
self._name = name
self._number = number
self._street = street
@property
def name(self):
return self._name
@property
def number(self):
return self._number
@property
def street(self):
return self._street
class IAdapter(metaclass=ABCMeta):
def __init__(self, adaptee):
self._adaptee = adaptee
@property
def adaptee(self):
return self._adaptee
@abstractproperty
def name(self):
pass
@abstractproperty
def address(self):
pass
class VendorAdapter(IAdapter):
@property
def name(self):
return self.adaptee.name
@property
def address(self):
return f'{self.adaptee.number} {self.adaptee.street}'
MOCK_VENDORS = (
VendorAdapter(Vendor('Dough Factory', 1, 'Semolina Court')),
VendorAdapter(Vendor('Farm Produce', 14, 'Country Rd.')),
VendorAdapter(Vendor('Cocoa World', 53, 'Tropical Blvd.'))
)
CUSTOMERS = MOCK_CUSTOMERS
for cust in CUSTOMERS:
print(f'Name: {cust.name}, Address: {cust.address}')
Name: Pizza Love, Address: 33 Peperoni Lane Name: Happy and Green, Address: 25 Kale St. Name: Sweet Tooth, Address: 42 Chocolate Ave.
CUSTOMERS = MOCK_VENDORS
for cust in CUSTOMERS:
print(f'Name: {cust.name}, Address: {cust.address}')
Name: Dough Factory, Address: 1 Semolina Court Name: Farm Produce, Address: 14 Country Rd. Name: Cocoa World, Address: 53 Tropical Blvd.
class VendorAdapter(Vendor, Customer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@property
def address(self):
return f'{self.number} {self.street}'
MOCK_VENDORS = (
VendorAdapter('Dough Factory', 1, 'Semolina Court'),
VendorAdapter('Farm Produce', 14, 'Country Rd.'),
VendorAdapter('Cocoa World', 53, 'Tropical Blvd.')
)
CUSTOMERS = MOCK_VENDORS
for cust in CUSTOMERS:
print(f'Name: {cust.name}, Address: {cust.address}')
Name: Dough Factory, Address: 1 Semolina Court Name: Farm Produce, Address: 14 Country Rd. Name: Cocoa World, Address: 53 Tropical Blvd.
Object Adapter
Class Adapter