2010年11月13日土曜日

第3章 Template Methodパターン : 具体的な処理をサブクラスにまかせる



この章の内容は、本文中にある次の一言に尽きます。
処理の骨組みをスーパークラスで記述し、具体的な肉付けをサブクラスで行っています。
新鮮に感じた部分は次の箇所。
  • 処理そのもの(templateMethod)はスーパークラスに書き、その処理のアルゴリズムを抽象メソッドで構築する
  • 抽象的なスーパークラスからの視点でサブクラスを見る
デザインパターンを勉強していて一番面白いのがこの新鮮さ。コードを書く意欲を駆り立てられます。

--

いつも通り、pythonで書いてみました。

実行結果
く け け け け け ガチャ
+--------------+
|逃げちゃダメだ|
|逃げちゃダメだ|
|逃げちゃダメだ|
|逃げちゃダメだ|
|逃げちゃダメだ|
+--------------+
+--------------------------------+
|It is not good ..running away...|
|It is not good ..running away...|
|It is not good ..running away...|
|It is not good ..running away...|
|It is not good ..running away...|
+--------------------------------+


ソースコード
#!/usr/bin/env python
# -*- coding: utf8 -*-

class AbstractDisplay:
    def __init__(self): raise NotImplementedError
    def openIt(self): raise NotImplementedError
    def printIt(self): raise NotImplementedError
    def closeIt(self): raise NotImplementedError
    def display(self):
        self.openIt()
        for i in xrange(5): self.printIt()
        self.closeIt()

class CharDisplay(AbstractDisplay):
    def __init__(self, ch): self.ch = ch
    def openIt(self): print u"く",
    def printIt(self): print self.ch,
    def closeIt(self): print u"ガチャ"

class StringDisplay(AbstractDisplay):
    def __init__(self, string): self.string = string
    def openIt(self): self.__printLine()
    def printIt(self): print "|%s|" % self.string
    def closeIt(self): self.__printLine()
    def __printLine(self):
        import sys
        sys.stdout.write('+')
        for i in xrange(len(self.string.encode("sjis"))): # byte-length of sjis is 2 while that of utf8 is 3
            sys.stdout.write('-')
        print '+'


def main():
    d1 = CharDisplay(u"け") # AbstractDisplay's instance
    d2 = StringDisplay(u"逃げちゃダメだ") # AbstractDisplay's instance
    d3 = StringDisplay("It is not good ..running away...") # AbstractDisplay's instance
    d1.display()
    d2.display()
    d3.display()

if __name__=='__main__': main()

pythonで書くのはpythonの勉強にはなるけど、型がないのでクラス構造が分かりにくくなってしまう問題があります。かといってC++で書くのもなあ

0 件のコメント:

コメントを投稿