LoginSignup
0
0

More than 1 year has passed since last update.

Factory Method (継承)の採用可否基準

Last updated at Posted at 2021-09-23
関連記事のトップページ
[シリーズ] Python におけるデザインパターンの記録

概要

基底クラスを継承をした構造 (Factory Method) の「採用可否の基準」と「実装例」.
引用元は下記書籍である.

ただし、内容について細かく記すと書籍の無断転載になるので大まかに記している.
また、コードは Ruby から Python に書き換えている.

引用元情報 一言
書籍 -- Rubyによるデザインパターン (Russ Olsen 著) 原書(英文)
GitHub -- 著者 Russ Olsen 氏

採用の基準

ここは独断もしくは私の解釈です.

採用基準は次を満すこと.
基底クラスの仕様が確定している状態にあること

言い換えると次である.
具象クラスのために基底クラスを変更しない状態にあること

上記が満せない場合は、Strategy Pattern を検討している.

コード例

ファイル構成

.
|-- ex3_vehicle.py
|-- ex4_car.py
`-- ex4_car_test.py

クラス図

Vehicle を基底クラスとして採用する場合、
具象クラスは必ず次の 3つを持つことが条件となる.

・重量 (weight)
・エンジン稼働 (start_engine)
・エンジン停止 (stop_engine)

つまり、自転車、馬車などエンジンを持たない乗り物を具象クラスとしてはいけない、
ということである.

(逆に、自転車や馬車などエンジンを持たない乗り物に対応する確率があるなら、
Strategy Pattern を使わないといけない)

image.png

./ex3_vehicle.py

基底クラス

#!/usr/bin/env python
# -*- encoding: utf-8 -*-

class Vehicle(object):
  def __init__(self, weight):
    self.weight = weight   #! 重さ
    print(f'This car weighs {self.weight}kg')

  def start_engine(self):  #! エンジン稼働
    print('start the engine')

  def stop_engine(self):   #! エンジン停止
    print('stop the engine')

./ex4_car.py

具象クラス

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from ex3_vehicle import *

class Car(Vehicle):
  def sunday_drive(self):
    self.start_engine()
    self.stop_engine()

./ex4_car_test.py

テストドライバ

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import unittest
from ex4_car import *

class CarTest(unittest.TestCase):
  def test_car(self):
    c = Car(weight=650)
    c.start_engine()
    c.stop_engine()
    c.sunday_driver()

実行例

$ python -m unittest ex4_car_test.py
This car weighs 650kg
start the engine
stop the engine
start the engine
stop the engine
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
0
0
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
0
0