目标 C——策略模式?
我理解“策略模式”的概念,但我仍然有点困惑。
假设我们有一个名为 Dog
的类。 Dog
有 MovementBehaviour
(接口),可以是 MovementBehaviourNormal
和 MovementBehaviourFast
。 MovementBehaviourNormal
和 MovementBehaviourFast
都包含名为 move
的方法。
问题:从 move
方法访问狗属性的最佳方法是什么? 将狗对象作为委托传递给 MovementBehaviour
是一个坏主意吗?
I understand the concept of the "strategy pattern" but I am still a little bit confused.
Let'say we have a class named Dog
.Dog
has MovementBehaviour
(interface) which can be MovementBehaviourNormal
and MovementBehaviourFast
.MovementBehaviourNormal
and MovementBehaviourFast
both contain a method named move
.
Question: what is the best way to access the dog attributes from the move
method?
Is it a bad idea to pass the dog object to MovementBehaviour
as a delegate?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一般来说,您不应该直接从策略对象访问 Dog 的属性。相反,您可以做的是提供一个 move 方法,该方法根据旧位置返回新位置。因此,例如,如果您有:
然后,当您实例化 Dog 时,您可以为其分配 NormalDogStrategy 并调用
[dog updatePosition]
- Dog 将询问其更新位置的策略,并分配到它的实例变量本身。您已经避免将 Dog 的内部结构暴露给 DogStrategy,并且仍然完成了您的预期。Generally, you shouldn't be accessing properties on Dog directly from your strategy object. Instead, what you can do is provide a move method that returns a new position based on the old position. So, for example, if you have:
Then, when you instantiate a Dog, you can assign it the NormalDogStrategy and call
[dog updatePosition]
- the Dog will ask its strategy for its updated position, and assign that to its instance variable itself. You've avoided exposing the internals of Dog to your DogStrategy and still accomplished what you intended.