[僕] Bridge パターン

僕ト云フ事

たろマークはてなブックマーク

2011年01月26日

[designpattern][python] Bridge パターン

ref. http://www.ceres.dti.ne.jp/~kaga/bridge.txt

 
# -*- coding: utf-8 -*-
 
import sys
 
class Display(object):
    def __init__(self, impl):
        self.__impl = impl
 
    def open(self):
        self.__impl.raw_open()
 
    def printf(self):
        self.__impl.raw_print()
 
    def close(self):
        self.__impl.raw_close()
 
    def display(self):
        self.open()
        self.printf()
        self.close()
 
 
class CountDisplay(Display):
    def __init__(self,impl):
        super(CountDisplay, self).__init__(impl)
 
    def multiDisplay(self,times):
        self.open()
        for i in range(1,times):
            self.printf()
 
        self.close()
 
class DisplayImpl():
    def raw_open(self):
        pass
 
    def raw_print(self):
        pass
 
    def raw_close(self):
        pass
 
 
class StringDisplayImpl(DisplayImpl):
    def __init__(self,string):
        self.__string = string
        self.__width = len(self.__string)
 
    def raw_open(self):
        self.print_line()
 
    def raw_print(self):
        print "|%s|" % self.__string
 
    def raw_close(self):
        self.print_line()
 
    def print_line(self):
        sys.stdout.write("+")
        for i in range(0,self.__width):
            sys.stdout.write("-")
 
        print "+"
 
 
if __name__ == '__main__':
    d1 = Display( StringDisplayImpl("Hello, Japan.") )
    d2 = CountDisplay( StringDisplayImpl("Hello, World.") )
    d3 = CountDisplay( StringDisplayImpl("Hello, Universe.") )
    d1.display()
    d2.display()
    d3.display()
 
    d3.multiDisplay(5)

python の print は改行がついてくるので、改行して欲しくないところは sys.stdout.write() で出力してる。

blog comments powered by Disqus