gpt4 book ai didi

design-patterns - GoF 对装饰器模式的解释令人困惑(或完全错误)

转载 作者:行者123 更新时间:2023-12-04 07:04:33 26 4
gpt4 key购买 nike

我正在讨论一些设计模式问题,并查看了 GoF 中装饰器模式的定义和示例。它说

Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.



它给出了使用继承的装饰器示例,但继承绝对不是动态的。

NetObjectives 犯了同样的错误:

http://www.netobjectives.com/PatternRepository/index.php?title=TheDecoratorPattern

Portland Pattern Repository 关于装饰器的讨论表明,关于什么是装饰器和不是装饰器存在混淆

http://c2.com/cgi/wiki?DecoratorPattern

Wikipedia 通过指出装饰器内部的委托(delegate)应该在构造时设置(其他 DI 技术也可以)来理解这种矛盾

http://en.wikipedia.org/wiki/Decorator_pattern

装饰器模式的所有示例(在 Java 或 C++ 中)都需要通过继承或实现接口(interface)的静态构造。 GoF 中的解释说,额外的职责是动态附加的。但这完全是错误的。

PPR 上的评论谈到了可以在运行时添加方法的动态语言,但是 Java 和 C++ 不是动态的,并且装饰器的解释并没有说它仅限于像 Groovy 和 Lisp 这样的动态语言。

对装饰器的正确解释难道不是说在不支持动态方法创建的语言中同时涉及静态和动态构造吗?

如他们自己的示例所示,GoF 的解释完全是错误的,还是我误解了什么?

最佳答案

动态
我认为“动态”一词的含义与 GOF 写这本书时有所不同。
我猜他们的意思是“在不实际修改底层对象的代码/定义的情况下向对象添加前/后行为”。对客户来说,对象(装饰与否)似乎是相同的。
今天动态与动态语言相关联,从这个意义上说,意味着松散的类型和在运行时向对象添加方法/行为的能力。

子类化的替代方法

The decorator pattern is an alternative to subclassing. Subclassing adds behavior at compile time, and the change affects all instances of the original class; decorating can provide new behavior at runtime for individual objects.

This difference becomes most important when there are several independent ways of extending functionality. In some object-oriented programming languages, classes cannot be created at runtime, and it is typically not possible to predict, at design time, what combinations of extensions will be needed. This would mean that a new class would have to be made for every possible combination. By contrast, decorators are objects, created at runtime, and can be combined on a per-use basis. -- wikipedia



装饰器使用继承,但它们不会从它们正在装饰的对象继承。它们继承公共(public)接口(interface),以便公开与装饰对象(模拟)相同的方法。他们将组合用于行为 - 通过委托(delegate)添加事前行为。
var dao = new PerformanceTrackingDecorator(new TurboSpeedDecorator(SqlDataAccessObject))
// use dao and later..
dao = new PerformanceTrackingDecorator(new TurboSpeedDecorator(XmlDataAccessObject))
//at runtime, I've added certain behavior to Sql and Xml DAOs

关于design-patterns - GoF 对装饰器模式的解释令人困惑(或完全错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3929996/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com