需要澄清 - 设计模式
在大多数设计模式概念中,都提到“Has A”比“Is A”更好。
在第一章 - Head First 设计模式 - “设计模式简介”的“集成 Duck 行为”部分(第 15 页)中,Duck 类引用了 FlyBehavior 和 QuackBehavior 接口类型。例如,我们要在功能中添加一个新行为,名称为 XYZBehavior(假设客户端尚未决定),我们需要更改 Duck 类以引用新接口。结果,我们需要改变类,但根据良好的设计模式,这是不应该发生的。
您能建议我如何处理这个要求吗?
In most of the design patterns concepts, it was mentioned that "Has A" is better than "Is A" means.
In the first chapter - Head First Design Patterns - "Intro to Design Patterns", section "Integrating the Duck Behaviour" (page no 15), the Duck class is having references to FlyBehavior and QuackBehavior interface types. For example, we are going to add a new behavior in feature name it XYZBehavior (just assume client has not yet decided it) for one kind of Ducks, we need to change the Duck class to have the reference to new interface. Resulting, we need to alter the class but which should not happen according to good design pattern.
Can you suggest me how can we deal with this requirement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这个问题可以通过使用依赖注入来解决
(在Java中通常通过Spring 或 Guice)
这是依赖注入初学者指南 基本上, Bird
会有一个 Behaviours 属性:
现在,在配置文件中,您可以指定将哪些 Behaviour 注入到 Bird 中,而无需更改 Bird 类。
That problem can be solved by using Dependency Injection
(In Java usually through either Spring or Guice)
Here's a Beginner's Guide to dependency Injection
Basically, a Bird would have a behaviors property:
Now in a Configuration file you would specify which Behaviors get injected into the Bird without having to change the Bird class.
如果您添加新行为(策略),策略模式不会阻止更改类。如果现有行为(策略)发生变化,它只是阻止接触类。
以 QuackBehaviour 为例:假设我们认为鸭子听起来像“quaack”,但经过几年的研究,我们意识到鸭子实际上听起来像“quaaack”。我们很幸运,我们实现了一个QuackBehaviour,只是调整了普通鸭子的QuackBehaviour接口的实现。这就是这个模式的技巧。
如果稍后我们决定添加 SwimBehaviour,因为另一个研究团队意识到游泳是一种常见的鸭子行为,那么我们必须触摸普通鸭子并添加该行为(到
Duck
类中) 。希望有帮助!
The Strategy pattern does not prevent from changing the class if you add a new behaviour (strategy). It just prevents from touching the class, if an existing behaviour (strategy) changes.
Example with QuackBehaviour: assume, we thought, a duck would sound like "quaack" but after some years of research we realised, that ducks actually sound like "quaaack". We're lucky, we implemented a QuackBehaviour and just adjust the implemtation of the QuackBehaviour interface for common ducks. That's the trick with this pattern.
If later on, we decide to add a SwimBehaviour, because another research team realized, that swimming is a common duck behaviour, then we have to touch the common duck and add that behaviour (to the
Duck
class).Hope it helped!
您可以使用
Composition
=> 来处理这种情况Duck
有一个Behaviours
列表。Duck
将维护一个Behavior 对象列表。在创建Duck
对象期间填充相关行为。示例代码:
You can handle this scenario by using
Composition
=>Duck
has a list ofBehaviours
.Duck
will maintain a list of Behaviour objects. Populate relevant behaviours during creation ofDuck
object.Sample code: