Pythonic方式在Bridge设计模式中设置属性

时间:2018-04-26 12:07:18

标签: python design-patterns

我正在尝试使用“Bridge”设计模式构建模块,以将抽象与其实现分离。我还需要一个可以在运行时动态更改的属性try_limit

经过一些试验和错误,我写了bridge.py,它按预期工作,但我需要分别在AbstractionImplementor类中编写属性和setter两次。还有另一种pythonic方法吗?

bridge.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import abc

class Abstraction(object):
    def __init__(self, imp):
        self._imp = imp

    @property
    def try_limit(self):
        return self._imp.try_limit

    @try_limit.setter
    def try_limit(self, value):
        self._imp.try_limit = value

    def run(self, cmd):
        ret = self._imp.run(cmd)

        return ret


class Implementor(metaclass=abc.ABCMeta):
    def __init__(self):
        self._try_limit = 0

    @property
    def try_limit(self):
        return self._try_limit

    @try_limit.setter
    def try_limit(self, value):
        self._try_limit = value

    @abc.abstractmethod
    def run(self, cmd):
        pass        


class ImpA(Implementor):
    def __init__(self, realtime_display=False):
        super().__init__()

    def run(self, arg):
    # Implement A which use try_limit
    # try_limit can be changed dynamically when running 


class ImpB(Implementor):
    def __init__(self):
        super().__init__()

    def run(self, arg):
    # Implement B which also use try_limit
    # try_limit can be changed dynamically when running

环境:Python 3.6.3

1 个答案:

答案 0 :(得分:0)

在阅读了Joe提供的wiki链接后,我发现我可以删除try_limit课程中的属性Implementor,因为我已将try_limit设置为实例' _imp'直。谢谢Joe& Jonrsharpe回答了我的问题。

bridge_revised.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import abc

class Abstraction(object):
    def __init__(self, imp):
        self._imp = imp

    @property
    def try_limit(self):
        return self._imp.try_limit

    @try_limit.setter
    def try_limit(self, value):
        self._imp.try_limit = value

    def run(self, cmd):
        ret = self._imp.run(cmd)

        return ret


class Implementor(metaclass=abc.ABCMeta):
    def __init__(self):
        self.try_limit = 0

    @abc.abstractmethod
    def run(self, cmd):
        pass        


class ImpA(Implementor):
    def __init__(self, realtime_display=False):
        super().__init__()

    def run(self, arg):
    # Implement A which use try_limit
    # try_limit can be changed dynamically when running 


class ImpB(Implementor):
    def __init__(self):
        super().__init__()

    def run(self, arg):
    # Implement B which also use try_limit
    # try_limit can be changed dynamically when running

环境:Python 3.6.3