代码之家  ›  专栏  ›  技术社区  ›  Lokesh Agrawal

如何在儿童课堂中实施和注入策略

  •  -1
  • Lokesh Agrawal  · 技术社区  · 7 年前

    有人能帮我理解一下,在子类中是否有更好的方法来实施注入策略(从常用策略列表中)。请在下面找到示例代码。

    我不完全相信将这些策略包装为静态方法,并提供基类中没有的策略价值。这是因为这里没有执行策略注入,而且使用继承来解决这个问题看起来并不自然/明显。

    我能以更好的方式实现这一点吗?

    def strategy1():
        print("strategy1")
    
    def strategy2():
        print("strategy2")
    
    class Base():
        strategy = None
    
    class Child1(Base):
        strategy = staticmethod(strategy1)
    
    class Child2(Base):
        strategy = staticmethod(strategy2)
    
    class Child3(Base):
        strategy = staticmethod(strategy1)
    
    Child1.strategy()
    Child2.strategy()
    Child3.strategy()
    

    我的主要要求是

    1. 跨继承层次结构重用代码(策略)
    2. 强制子类在重写基类时注入这些策略。
    1 回复  |  直到 7 年前
        1
  •  1
  •   Bob Zimmermann    7 年前

    您可以改为使用策略类,将策略函数注入其中:

    import abc
    
    def strategy1(self):
        print("strategy1")
    
    class AbstractClient(metaclass=abc.ABCMeta):
        @abc.abstractmethod
        def execute(self):
            pass
    
    class StrategizedClient(AbstractClient):
        execute = strategy1
    
    class PlanlessClient(AbstractClient):
        pass
    

    这需要python3,但它将强制您的子类注入一种策略:

    >>> StrategizedClient()
    <strategy.StrategizedClient object at 0x10fd594a8>
    >>> PlanlessClient()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: Can't instantiate abstract class PlanlessClient with abstract methods execute