jeudi 26 avril 2018

Pythonic way to setup property in Bridge design pattern

[Description]

  • I'm trying to build a module by using "Bridge" design pattern to decouple an abstraction from its implementation. I also need a property "try_limit" can be changed dynamically when running.
  • After some tries & errors, I wrote bridge.py which works as I expected, but I need to write property & setter twice in "Abstraction" & "Implementor" class respectively. Is there another pythonic way to do this?

  • 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
    
    

[Environment]

  • Python 3.6.3

Aucun commentaire:

Enregistrer un commentaire