gpt4 book ai didi

design-patterns - 策略模式 : coupled strategy vs uncoupled strategy

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

耦合策略和非耦合策略有什么区别?

谢谢回答。

最佳答案

当策略类知道上下文时,或者当客户端知道策略具体类时,策略是耦合的。

我们可以阅读 here (有一些小的修改):

Usually each strategy need data from the context or have to return some processed data to the context. This can be achieved in 2 ways.

  1. creating some additional classes to encapsulate the specific data.
  2. passing the context object itself to the strategy objects. The strategy object can set returning data directly in the context.

When data should be passed, the drawbacks of each method should be analyzed. For example, if some classes are created to encapsulate additional data, a special care should be paid to what fields are included in the classes. Maybe in the current implementation all required fields are added, but maybe in the future some new strategy concrete classes require data from context which are not included in those additional classes. Another fact should be specified at this point: it's very likely that some of the strategy concrete classes will not use fields passed to it in the additional classes.



如果上下文对象被传递给策略,那么我们在策略和上下文之间就有了耦合。

关于策略和客户端之间的耦合,在同一页面中我们阅读:

In the classic implementation of the pattern the client should be aware of the strategy concrete classes. In order to decouple the client class from strategy classes is possible to use a factory class inside the context object to create the strategy object to be used. By doing so the client has only to send a parameter (like a string) to the context asking to use a specific algorithm, being totally decoupled of strategy classes.



无论上下文是谁决定策略,解耦都是将具体的策略对象注入(inject)到客户端,所以客户端不知 Prop 体是哪个实现,也不知道还有哪些其他的实现。

因此,解耦实现是没有人知道其他具体参与者的情况。

关于design-patterns - 策略模式 : coupled strategy vs uncoupled strategy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21456722/

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