谁能解释一下策略模式与控制反转有何关系?

发布于 2024-07-11 21:26:22 字数 27 浏览 9 评论 0原文

谁能准确解释策略模式与控制反转有何关系?

Can anyone explain exactly how the Strategy Pattern relates to Inversion of Control?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

梦亿 2024-07-18 21:26:23

当您使用策略模式时,您希望其他类依赖于接口而不是具体的策略。 实现此目的的一种方法是将具体策略注入到使用它作为接口的类中,而不是让该类了解如何创建适当的策略。 这就是 IoC/依赖注入的用武之地。

这个想法是你有某种配置或决策类来定义要使用的策略。 这可能是一个 IoC 框架,但不一定是。 此类负责根据系统状态或配置使用适当的策略配置其他类。 具体策略是通过构造函数或属性设置器创建和注入的,因此对实例化策略类的“控制”是“反向的”——它不是由依赖于它的类完成的,而是从外部完成的。

When you use the strategy pattern, you want your other classes to depend on the interface rather than a concrete strategy. One way to do this is to have the concrete strategy injected into a class that uses it as the interface rather than having the class understand how to create the appropriate strategy. This is where IoC/Dependency Injection comes in.

The idea would be that you have some sort of configuration or decision class that defines which strategies to use. This could be an IoC framework, but it doesn't necessarily have to be. This class is responsible for configuring your other classes with the appropriate strategy based on system state or configuration. The concrete strategy is created and injected via a constructor or property settor and thus "control" over which strategy class is instantiated is "inverted" -- it is not done by the class depending on it but, rather, from outside.

笛声青案梦长安 2024-07-18 21:26:23

就其本身而言,该模式不会引入控制反转。 如果模式的开发人员实现它,以便将可交换算法注入到控制器中,那么这就是反转。 另一方面,如果实现者从其他来源获取要使用的算法(例如配置,或通过其他方式在控制器的构造函数中确定它),那么它只是您的普通类型的代码。

On its own, the pattern does not introduce inversion of control. If the developer of the pattern implements it such that the swappable algorithm is injected into the controller, then that is inversion. If the implementor, on the other hand, gets the algorithm to use from some other source (such as configuration, or determines it in the constructor of the controller via some other means), then it's just your run-of-the-mill type of code.

木森分化 2024-07-18 21:26:23

没有 IOC 是完全不同的事情,您可以在此处阅读有关 IOC 和 DI 的更多信息,了解实际想法

http://www.codeproject.com/KB/aspnet/IOCDI.aspx

No IOC is a different thing all together , you can read more about IOC and DI here top get the actual idea

http://www.codeproject.com/KB/aspnet/IOCDI.aspx

奈何桥上唱咆哮 2024-07-18 21:26:23

IOC 可以被认为是可以使用策略模式(手段)来实现的主体(目的),因为服务定位器模式将是另一种选择。

IOC could be thought of as a principal (ends) that can be achieved using the strategy pattern (means) as servicelocator pattern would be another option.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文