谁应该实例化和分配运行时策略实现?
实现策略模式时,如何确定哪个类负责 for:
选择要传递给 Context 类的具体具体策略实现(假设选择是基于一些复杂的业务逻辑而不是静态标志)
实例化上述具体实现并实际将其注入到 Context 类中
感觉应该有一些客观的指导来涵盖这一点。我已经阅读了各种 OOP 模式(即 GRASP 和 SOLID),但我仍然对这个特定问题不太清楚。
When implementing the strategy pattern, how do you determine which class is responsible
for:
Selecting the specific concrete strategy implementation to pass to the Context class (assuming that the selection is based on some complex business logic and not a static flag)
Instantiating the aforementioned concrete implementation and actually injecting it into the Context class
It feels like there ought to be some objective guidance out there that covers this. I've done some reading on various OOP patterns (i.e. GRASP and SOLID) but I still don't have a lot of clarity around this particular question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这与我在 DI 容器中遇到的问题非常接近。看看这里,Mark Seemann 提供了一个很好的答案。
This is very close to the issues I was having with a DI container. Have a look here, Mark Seemann has provided a great answer.
如果您正在尝试解决特定情况,那么您正在寻找抽象工厂模式。工厂根据运行时信息确定如何实例化一系列类型。
如果您想知道如何抽象地解决这种情况,您正在寻找控制反转容器,管理依赖关系的组织和实现。策略的注册将包括条件逻辑。
If you are trying to address a particular situation, you are looking for the abstract factory pattern. A factory determines how to instantiate a family of types based on runtime information.
If you are wondering how to address this situation in the abstract, you are looking for an Inversion of Control container, which manages the organization and fulfillment of dependencies. The registration of the strategy would include the conditional logic.
这个决定是特定于上下文的,就像设计模式的其他所有内容一样。引用 GoF 书中的内容(斜体是我的):
...
That determination is context-specific, just like everything else with Desing Patterns. Quoting from the GoF book (italics mine):
...