nono blog
楽しい人生を送りたい!
ITスキル

pythonプログラム デザインパターン(Bridge)

Bridgeパターンとは

(概要)
各機能を構成している要素を抽象クラスでつないで、柔軟に機能追加を行う
(継承元の変更を影響範囲を限定する(継承先への影響をできるだけ減らす)ため、
 継承する階層が深層化しないようにする。

(目的)
機能拡張が容易にできるようにして、拡張時に他のクラスに影響がないようにする。

(構成要素)
Implementer : 基本的な機能を記述したインターフェース
ConcreteImplementer : Implementerを継承して処理を具体的に記述するクラス
Abstraction : 追加として実装される機能をimplementerと切り離して
作成する処理を記述した抽象クラス
RefinedAbstraction : Abstractionの処理を具体的に記述したクラス

pythonサンプルコード

Bridgeパターンのpythonによるサンプルコード

# bridge.py

from abc import ABC, abstractmethod


# Imprementer
class Shape(ABC):

    def __init__(self, width, height):
        self._width = width
        self._height = height

    @abstractmethod
    def create_shape_str(self):
        pass


#ConcreteImprementer
class RectangleShape(Shape):

    def __init__(self, width, height):
        super().__init__(width, height)

    def create_shape_str(self):
        rectangle = '*' * self._width + '\n'
        for _ in range(self._height - 2):
            rectangle += '*' + ' ' * (self._width - 2) + '*' + '\n'
        rectangle += '*' * self._width + '\n'
        return rectangle


class SquareShape(Shape):

    def __init__(self, width, height=None):
        super().__init__(width, width)

    def create_shape_str(self):
        square = '*' * self._width + '\n'
        for _ in range(self._width - 2):
            square += '*' + ' ' * (self._width - 2) + '*' + '\n'
        square += '*' * self._width + '\n'
        return square


# Bridge pattern
class WriteAbstraction(ABC):

    def __init__(self, shape: Shape):
        self._shape = shape

    def read_shape(self):
        return self._shape.create_shape_str()

    @abstractmethod
    def write_to_text(self, file_name):
        pass


class WriteShape(WriteAbstraction):

    def write_to_text(self, file_name):
        with open(file_name, mode='w', encoding='utf-8') as fh:
            fh.write(self.read_shape())


if __name__ == '__main__':

    rectangle = RectangleShape(10, 5)
    square = SquareShape(10)
    print(rectangle.create_shape_str())
    print(square.create_shape_str())

    write_rectangle = WriteShape(rectangle)
    write_rectangle.write_to_text('rectangle.txt')
    write_square = WriteShape(square)
    write_square.write_to_text('square.txt')