2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Pythonデザインパターン - Template Method

Last updated at Posted at 2021-04-07

Pythonデザインパターン - Template Method

概要

スーパークラスで処理の枠組みを決めて、サブクラスで枠組みを決める。
スーパークラスのテンプレートメソッドでアルゴリズムが記述されていますので、
サブクラス側では アルゴリズムをいちいち記述する必要がなくなる。
そして、Template Methodパターンでプログラミングしていれば、
テンプレートメソッドに誤りが発見された場合でも、テンプレートメソッドさえ修正すればよいというその後の修正の手間を抑えることができる。
Pythonでは抽象クラスを書く場合はABCモジュールを利用して実装することができる。

具体例:

プログラム例:
LIST・TABLE表示

abstract_display.py

from abc import ABCMeta, abstractmethod

class AbstractDisplay(metaclass=ABCMeta):

    _data = list()
	
    def __init__(self, data):
        self._data = data

    @abstractmethod 
    def display_header(self):
        pass

    @abstractmethod     
    def display_body(self):
        pass

    @abstractmethod 
    def display_footer(self):
        pass

    def get_data(self):
        return self.data

    def display(self):
        self.display_header()
        self.display_body()
        self.display_footer()

list_display.py

from abstract_display import AbstractDisplay

class ListDisplay(AbstractDisply):

    def display_header(self):
		print('<dl>')

	def display_body(self):
		for k, v in self.get_data.items(): 
			print( '<dt>' + $key + '</dt>')
            print( '<dd>' + $value + '</dd>')
		
    def display_footer(self):
		print('</dl>')

table_display.py

from abstract_display import AbstractDisplay

class TableDisplay(AbstractDisply):

    def display_header(self):
		print('<table border="1">')

	def display_body(self):
		for k, v in self.get_data.items(): 
			print('<tr>')
			print('<th>' + $key + '</th>')
            print('<td>' . $value . '</td>')
            print('</tr>')
		
    def display_footer(self):
		print('</table>')

main.py

from list_display import ListDisplay
from table_display import TableDisplay

if __name__ == '__main__':
	data = [
		'Morita', 'Yamada', 'Satou',
	]
	
	display1 = ListDisplay()
	display1.display()
	
	display2 = TableDisplay()
	display2.display()

出力

<dl>
<dt>0</dt>
<dd>Morita</dd>
<dt>1</dt>
<dd>Yamada</dd>
<dt>2</dt>
<dd>Satou</dd>
</dl>
<table border="1">
<tr>
<th>0</th>
<td>Morita</td>
</tr>
<tr>
<th>1</th>
<td>Yamada</td>
</tr>
<tr>
<th>2</th>
<td>Satou</td>
</tr>
</table>

他デザインパターンも更新予定:writing_hand:
いいね!と思ったら LGTM お願いします :clap::clap::clap:

【PR】プログラミング新聞リリースしました! → https://pronichi.com
【PR】週末ハッカソンというイベントやってます! → https://weekend-hackathon.toyscreation.jp/about/

2
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?