Learn the design pattern "Adapter" in Python

As a material for learning GoF design patterns, the book "Introduction to Design Patterns Learned in the Augmented and Revised Java Language" seems to be helpful. However, since the examples taken up are based on JAVA, I tried the same practice in Python to deepen my understanding.

■ Adapter (adapter pattern)

The Adapter pattern is one of the design patterns defined by GoF (Gang of Four; 4 gangs). The Adapter pattern allows you to change the interface without modifying an existing class. There are "** method using inheritance " and " method using delegation **" as a method to realize the Adapter pattern.

UML class diagram W3sDesign_Adapter_Design_Pattern_UML.jpg

1. Adapter using inheritance

Adapter using inheritance is realized by creating a subclass of the class you want to use and implementing the necessary interface for that subclass. inheritence.png

2. Adapter using delegation

Adapter using delegation is realized by creating an instance of the class you want to use and using that instance from another class. delegation.png (The above is quoted from Wikipedia)

■ "Adapter" sample program

Actually, I would like to run a sample program that utilizes the Adapter pattern and check the following behavior.

--Display character strings in parentheses --Indicate with * marks before and after the character string

$ python Main.py 
(Hello)
*Hello*

■ Details of sample program

Similar code has been uploaded to the Git repository. https://github.com/ttsubo/study_of_design_pattern/tree/master/Adapter

--Directory structure

.
├── Main.py
└── adapter
    ├── __init__.py
    ├── banner.py
    ├── print.py
    └── print_banner.py

(1) Role of Target

The Target role defines the interface involved in the behavior of the instance. In the sample program, the Print class serves this role.

adapter/print.py


from abc import ABCMeta, abstractmethod

class Print(metaclass=ABCMeta):
    @abstractmethod
    def printWeak(self):
        pass

    @abstractmethod
    def printStrng(self):
        pass

(2) The role of Client

It is a role to work by using the method of the role of Target. In the sample program, the startMain method serves this role.

Main.py


from adapter.print_banner import PrintBanner

def startMain():
    p = PrintBanner("Hello")
    p.printWeak()
    p.printStrng()

if __name__ == '__main__':
    startMain()

(3) The role of Adaptee

Here we implement the method that actually works in the role of ʻAdapter. In the sample program, the Banner` class serves this role.

adapter/banner.py


class Banner(object):
    def __init__(self, string):
        self.__string = string

    def showWithParen(self):
        print("({0})".format(self.__string))

    def showWithAster(self):
        print("*{0}*".format(self.__string))

(4) Role of Adapter (fitting side)

The ʻAdapterrole is a class that implements the interface for theTargetrole. In the sample program, thePrintBanner` class serves this role. There are the following two methods for realizing the Adapter pattern.

--Method using inheritance --Method using delegation

□ Sample program using inheritance

adapter/print_banner.py


from adapter.banner import Banner
from adapter.print import Print

class PrintBanner(Banner, Print):
    def __init__(self, string):
        super(PrintBanner, self).__init__(string)

    def printWeak(self):
        self.showWithParen()

    def printStrng(self):
        self.showWithAster()

□ Sample program using delegation

adapter/print_banner.py


from adapter.banner import Banner
from adapter.print import Print

class PrintBanner(Print):
    def __init__(self, string):
        self.__banner = Banner(string)

    def printWeak(self):
        self.__banner.showWithParen()

    def printStrng(self):
        self.__banner.showWithAster()

■ Reference URL

-[Finishing "Introduction to Design Patterns Learned in Java Language" (Not)](https://medium.com/since-i-want-to-start-blog-that-looks-like-men-do/java Introduction to Design Patterns Learned in Language-Finishing-Not-2cc9b34a30b2) -Adapter pattern from "diary of tachikawa844"

Recommended Posts

Learn the design pattern "Adapter" in Python
Learn the design pattern "Prototype" in Python
Learn the design pattern "Builder" in Python
Learn the design pattern "Flyweight" in Python
Learn the design pattern "Observer" in Python
Learn the design pattern "Memento" in Python
Learn the design pattern "Proxy" in Python
Learn the design pattern "Command" in Python
Learn the design pattern "Visitor" in Python
Learn the design pattern "Bridge" in Python
Learn the design pattern "Mediator" in Python
Learn the design pattern "Decorator" in Python
Learn the design pattern "Iterator" in Python
Learn the design pattern "Strategy" in Python
Learn the design pattern "Composite" in Python
Learn the design pattern "State" in Python
Learn the design pattern "Abstract Factory" in Python
Learn the design pattern "Factory Method" in Python
Learn the design pattern "Chain of Responsibility" in Python
Learn the design pattern "Facade" with Python
Implement the Singleton pattern in Python
Design Pattern #Adapter
Singleton pattern in Python
Visitor pattern in Python
Download the file in Python
Find the difference in Python
I wrote a design pattern in kotlin Adapter edition
Learn cumulative sum in Python
Design Patterns in Python: Introduction
Learn exploration in Python # 1 Full exploration
Python Design Pattern --Template method
Getting the arXiv API in Python
Python in the browser: Brython's recommendation
Save the binary file in Python
Hit the Sesami API in Python
Get the desktop path in Python
Get the script path in Python
In the python command python points to python3.8
Hit the web API in Python
I wrote the queue in Python
Calculate the previous month in Python
Examine the object's class in python
Get the host name in Python
Access the Twitter API in Python
The first step in Python Matplotlib
I wrote the stack in Python
Master the weakref module in Python
Learn the basics of Python ① Beginners
Load the remote Python SDK in IntelliJ
Try using the Wunderlist API in Python
Check the behavior of destructor in Python
[Python Kivy] About changing the design theme
Learn the basics while touching python Variables
OR the List in Python (zip function)
GoF design pattern from the problem 2. Structure
Display Python 3 in the browser with MAMP
Tweet using the Twitter API in Python
Check if the URL exists in Python
Associate the table set in python models.py
Run the Python interpreter in a script
The result of installing python in Anaconda