Skip to content

Commit

Permalink
Type checked adapter pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
rednafi committed Jun 27, 2020
1 parent cb5b5fb commit 44ce0a5
Showing 1 changed file with 22 additions and 16 deletions.
38 changes: 22 additions & 16 deletions patterns/structural/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,58 +28,63 @@
Allows the interface of an existing class to be used as another interface.
"""

from typing import Callable, TypeVar

T = TypeVar("T")


class Dog:
def __init__(self):
def __init__(self) -> None:
self.name = "Dog"

def bark(self):
def bark(self) -> str:
return "woof!"


class Cat:
def __init__(self):
def __init__(self) -> None:
self.name = "Cat"

def meow(self):
def meow(self) -> str:
return "meow!"


class Human:
def __init__(self):
def __init__(self) -> None:
self.name = "Human"

def speak(self):
def speak(self) -> str:
return "'hello'"


class Car:
def __init__(self):
def __init__(self) -> None:
self.name = "Car"

def make_noise(self, octane_level):
return "vroom{0}".format("!" * octane_level)
def make_noise(self, octane_level: int) -> str:
return f"vroom{'!' * octane_level}"


class Adapter:
"""
Adapts an object by replacing methods.
Usage:
"""Adapts an object by replacing methods.
Usage
------
dog = Dog()
dog = Adapter(dog, make_noise=dog.bark)
"""

def __init__(self, obj, **adapted_methods):
"""We set the adapted methods in the object's dict"""
def __init__(self, obj: T, **adapted_methods: Callable):
"""We set the adapted methods in the object's dict."""
self.obj = obj
self.__dict__.update(adapted_methods)

def __getattr__(self, attr):
"""All non-adapted calls are passed to the object"""
"""All non-adapted calls are passed to the object."""
return getattr(self.obj, attr)

def original_dict(self):
"""Print original object dict"""
"""Print original object dict."""
return self.obj.__dict__


Expand Down Expand Up @@ -116,4 +121,5 @@ def main():

if __name__ == "__main__":
import doctest

doctest.testmod(optionflags=doctest.ELLIPSIS)

0 comments on commit 44ce0a5

Please sign in to comment.