中间件是装饰器模式的实现吗?
Are middlewares an implementation of the Decorator pattern?
在Django中,有中间件的思想。它包括更改请求并将其传递给下一个中间件等,然后对响应执行相反的操作。
中间件是Decorator设计模式的实现吗?它们是装饰者的特例吗?它们之间有什么区别?
还有,Django中Decorator的实现和GoF的描述有什么区别?
中间件本身不是装饰器,但可以使用 Django 中的几个 built in functions 从中间件中制作装饰器:
def decorator_from_middleware(middleware_class):
"""
Given a middleware class (not an instance), return a view decorator. This
lets you use middleware functionality on a per-view basis. The middleware
is created with no params passed.
"""
return make_middleware_decorator(middleware_class)()
def decorator_from_middleware_with_args(middleware_class):
"""
Like decorator_from_middleware, but return a function
that accepts the arguments to be passed to the middleware_class.
Use like::
cache_page = decorator_from_middleware_with_args(CacheMiddleware)
# ...
@cache_page(3600)
def my_view(request):
# ...
"""
return make_middleware_decorator(middleware_class)
中间件和装饰器很相似,可以做同样的工作。它们提供了一种在 chain/stack.
下游其他效果之前或之后插入中间效果的方法
不同之处在于中间件管道是使用缩减来计算的,该缩减为中间件提供了一个更简单的接口,该接口隐藏了链中的下一个中间件对象。相反,它提供了一个 next
函数,该函数使用正确的接口(例如 IHandler.handle
)将消息应用于该对象。
另一个区别是动态add/remove中间件更容易,因为它存在于容器对象的中间(例如在数组中)并且管道可以按需组装。一个装饰器是一堆俄罗斯套娃,它的套娃不能那么容易地重新组合。
在Django中,有中间件的思想。它包括更改请求并将其传递给下一个中间件等,然后对响应执行相反的操作。
中间件是Decorator设计模式的实现吗?它们是装饰者的特例吗?它们之间有什么区别?
还有,Django中Decorator的实现和GoF的描述有什么区别?
中间件本身不是装饰器,但可以使用 Django 中的几个 built in functions 从中间件中制作装饰器:
def decorator_from_middleware(middleware_class):
"""
Given a middleware class (not an instance), return a view decorator. This
lets you use middleware functionality on a per-view basis. The middleware
is created with no params passed.
"""
return make_middleware_decorator(middleware_class)()
def decorator_from_middleware_with_args(middleware_class):
"""
Like decorator_from_middleware, but return a function
that accepts the arguments to be passed to the middleware_class.
Use like::
cache_page = decorator_from_middleware_with_args(CacheMiddleware)
# ...
@cache_page(3600)
def my_view(request):
# ...
"""
return make_middleware_decorator(middleware_class)
中间件和装饰器很相似,可以做同样的工作。它们提供了一种在 chain/stack.
下游其他效果之前或之后插入中间效果的方法不同之处在于中间件管道是使用缩减来计算的,该缩减为中间件提供了一个更简单的接口,该接口隐藏了链中的下一个中间件对象。相反,它提供了一个 next
函数,该函数使用正确的接口(例如 IHandler.handle
)将消息应用于该对象。
另一个区别是动态add/remove中间件更容易,因为它存在于容器对象的中间(例如在数组中)并且管道可以按需组装。一个装饰器是一堆俄罗斯套娃,它的套娃不能那么容易地重新组合。