【发布时间】:2014-03-07 11:30:17
【问题描述】:
我想创建一个使用类似这样的策略设计模式的类:
class C:
@staticmethod
def default_concrete_strategy():
print("default")
@staticmethod
def other_concrete_strategy():
print("other")
def __init__(self, strategy=C.default_concrete_strategy):
self.strategy = strategy
def execute(self):
self.strategy()
这给出了错误:
NameError: name 'C' is not defined
将strategy=C.default_concrete_strategy 替换为strategy=default_concrete_strategy 将起作用,但默认情况下,策略实例变量将是静态方法对象而不是可调用方法。
TypeError: 'staticmethod' object is not callable
如果我删除 @staticmethod 装饰器,它会起作用,但还有其他方法吗?我希望自行记录默认参数,以便其他人立即看到如何包含策略的示例。
另外,有没有更好的方法来公开策略而不是静态方法?我认为在这里实现完整的类没有意义。
【问题讨论】:
-
策略模式在python中大多没用。由于您将函数作为第一类对象,因此您可以传递函数。
-
@Bakuriu 正如您所见,该策略是一流的对象函数。我认为这仍然被称为策略模式不是吗?
-
是的,但是策略模式主要是在不允许传递函数的语言中发明的。我的意思是,在你的类的 99% 的用例中,你可以简单地直接传递函数并以更低的复杂性获得相同的结果。
-
@Bakuriu 你能举例说明如何做到这一点吗?
标签: python python-3.x static-methods strategy-pattern default-parameters