我参加了有关装饰器模式的会议,其中提供的大多数示例都在java中.例如,在Pizza对象下面的示例中,装饰有两个浇头.
Pizza vegPizza = new ToppingsType1(new ToppingType2(new Pizza()))
在python中,我已经看到装饰器在这样的场景中使用
@applyTopping2
@applyTopping1
makePizza():
pass
尽管在这里我可以看到makePizza函数由两个函数修饰,但是它与基于Java的基于类的方法有很大不同.
我的问题是python装饰器严格执行装饰器模式,还是实现有所不同,但思路相同.
PS:我不确定在哪里可以找到装饰器模式的标准定义.
解决方法:
您应该read this,这说明了什么是python的装饰器.
The “decorators” we talk about with concern to Python are not exactly the same thing as the 07001 […]. A Python decorator is a specific change to the Python syntax that allows us to more conveniently alter functions and methods (and possibly classes in a future version). This supports more readable applications of the 07001 but also other uses as well.
因此,您将能够使用python的装饰器实现“经典”装饰器模式,但是您将能够使用这些装饰器做更多(有趣的事情)的事情.
就您而言,它可能类似于:
def applyTopping1(functor):
def wrapped():
base_pizza = functor()
base_pizza.add("mozzarella")
return base_pizza
return wrapped
def applyTopping2(functor):
def wrapped():
base_pizza = functor()
base_pizza.add("ham")
return base_pizza
return wrapped
然后你会得到一个玛格丽特:)