doc.dev1x.org

Bridge

1. 目的

2. 課題

3. 解決策

class Feature:
    def __init__(self, impl):
        self.impl = impl

    def exec(self):
        self.impl.exec()

class Implement():
    def exec(self):
        print('Year!')

if __name__ == '__main__':
    f = Feature(Implement())
    f.exec()  # Year!

4. メリット

5. デメリット

構造が複雑になる

6. 注意事項

(1) Factoryパターンとの併用必須

class Feature:
    def __init__(self, impl):
        self.impl = impl

    def exec(self):
        self.impl.exec()

class Factory:
    @classmethod
    def create(cls, impl_type):
        if impl_type == '01': return Implement01()
        if impl_type == '02': return Implement02()
        raise ValueError('invalid argument')

class Implement(metaclass=ABCMeta):
    @abstractmethod
    def exec(self):
        pass

class Implement01(Implement):
    def exec(self):
        ...

class Implement02(Implement):
    def exec(self):
        ...


if __name__ == '__main__':
    impl1 = Factory.create('01')
    f1 = Feature(impl1)
    f1.exec()

    impl2 = Factory.create('02')
    f2 = Feature(impl2)
    f2.exec()

(2) クロージャならクラスを定義する必要なし

class Feature:
    def __init__(self, fn):
        self.fn = fn

    def exec(self):
        self.fn()

def function1():
    print("実装1")

def function2():
    print("実装2")


if __name__ == '__main__':
    f1 = Feature(function1)
    f1.exec()

    f2 = Feature(function2)
    f2.exec()

参考資料

Appendix-1