Python基礎 オブジェクト指向 1(Template Method) 「振る舞い」に関するデザインパターン
| 登録日 | :2025/09/19 05:50 |
|---|---|
| カテゴリ | :Python基礎 |
Template Methodとは
親クラスで処理の枠組みを定めて、子クラスで枠組みの具体的な内容を定めるようなパターン
処理フローがほとんど同じで、その中の一部の処理内容が異なる場合に、その異なる処理の部分だけを子クラスに実装させる
「振る舞い」に関するデザインパターン
Template Methodの構成要素
AbstractClass
- 抽象クラス
- 処理全体の流れを決定するテンプレートメソッド
- テンプレートメソッドで使用する抽象メソッド
ConcreteClass
- AbstractClassを継承したクラス
- AbstractClassで定義された抽象メソッドを実装
Template Methodのメリット・デメリット
メリット
- 共通な処理を親クラスでまとめることができる
- 処理全体の流れは変えずに、子クラスごとに一部の処理内容を変えることができる
デメリット
- 処理全体の流れが親クラスに決められるので、子クラスの拡張が制限される
- 子クラスで親クラスのメソッドの振る舞いを変えてしまうと、リスコフの置換原則に違反する
サンプルコード
from abc import ABCMeta, abstractmethod
class TestTemplate(metaclass=ABCMeta):
def __init__(self):
self.setup()
self.execute()
self.teardown()
@abstractmethod
def setup(self):
pass
@abstractmethod
def execute(self):
pass
@staticmethod
def teardown():
print('teardown')
class ItemServiceTest(TestTemplate):
def setup(self):
print("setup: ItemServiceTest")
def execute(self):
print("execute: ItemServiceTest")
class UserServiceTest(TestTemplate):
def setup(self):
print("setup: UserServiceTest")
def execute(self):
print("execute: UserServiceTest")
if __name__ == '__main__':
item = ItemServiceTest()
user = UserServiceTest()