有人可以帮助我了解是否有更好的方法在子类中强制执行注入策略(来自常用策略列表)。请在下面找到示例代码。我并不完全相信将这些策略包装为静态方法并在基类中将策略的值提供为 None 。这是因为这里没有执行策略注入,并且使用继承解决这个问题看起来并不自然/明显。我能以更好的方式实现这一目标吗?def strategy1(): print("strategy1")def strategy2(): print("strategy2")class Base(): strategy = Noneclass Child1(Base): strategy = staticmethod(strategy1)class Child2(Base): strategy = staticmethod(strategy2)class Child3(Base): strategy = staticmethod(strategy1)Child1.strategy()Child2.strategy()Child3.strategy()我的主要要求是跨继承层次结构的代码(策略)重用强制子类在覆盖基类时注入这些策略。
1 回答

汪汪一只猫
TA贡献1898条经验 获得超8个赞
您可以改为使用将策略函数注入的策略类:
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
添加回答
举报
0/150
提交
取消