実装継承を使うタイミング
委譲より実装継承を使う、というかStrategyよりTemplate Methodを使うのは、
クラス独自の機能追加が必要なときではないかと思います。
pythonのthreading.Threadクラスは、
runメソッドをオーバーライドすると、
runの中身を実行するスレッドを作れます。
Template Methodパターンの実例です。
from threading import Thread class HelloThread(Thread): """hello world ! を表示し続けるスレッド""" def run(self): while 1: print "hello world!"
もちろん、Strategyパターンにする事もできます。
class StrategyThread(Thread): def __init__(self, callable): Thread.__init__(self) self._callable = callable def run(self): self._callable = callable def HelloThread(): def hello(): while 1: print "hello world!" return StrategyThread(hello)
このHelloThreadは、永久に挨拶を表示させ続けてしまうので、
Template Method版HelloThreadに、停止する機能を追加してみます。
from threading import Thread class HelloThread(Thread): """hello world ! を表示し続けるスレッド""" def __init__(self): Thread.__init__(self) self._stop = False def run(self): while not self._stop: print "hello world!" def stop(self): self._stop = True
これを、Strategy版HelloThreadで実現するのは困難だと思います。
クラスそのものに変更が必要な機能追加だからです。
threading.Threadは
サブクラスに独自の機能(上の場合、stop())を追加する公算が非常に大きいため、
Template Method採用しているのでしょう。
例外がExceptionを継承するのも、一つの理由は機能追加だと思います。