🔋
Adapterパターンを学ぶ【Python】
一言で言うと
変換。別名Wrappaerパターン。
コードサンプル
移譲での実装パターン。
ディレクトリ構造
adaptor/
├── banner.py
├── main.py
├── print.py
└── print_banner.py
main.py
from print import Print
from print_banner import PrintBanner
def main() -> None:
p: Print = PrintBanner('Hello')
p.printWeek()
p.printStrong()
if __name__ == '__main__':
main()
banner.py
class Banner():
def __init__(self, string: str) -> None:
self.string: str = string
def showWithParen(self) -> None:
print(f'({self.string})')
def showWithAster(self) -> None:
print(f'*{self.string}*')
print.py
from abc import ABCMeta, abstractmethod
class Print(metaclass=ABCMeta):
@abstractmethod
def printWeek(self) -> None:
pass
@abstractmethod
def printStrong(self) -> None:
pass
print_banner.py
from print import Print
from banner import Banner
class PrintBanner(Print):
def __init__(self, string: str) -> None:
self.banner: Banner = Banner(string)
def printWeek(self) -> None:
self.banner.showWithParen()
def printStrong(self) -> None:
self.banner.showWithAster()
Discussion