具有默认策略的策略模式
在设计模式方面,我是一个初学者。关于实现策略模式的任何想法/如下:
public class SomeClass { private Strategy strategy = new DefaultStrategy(); public void provideCustomStrategy(Strategy strategy) { this.strategy = strategy; } }
这将确保松散耦合以及策略模式和 DI 的所有其他好处。同时,您不强迫用户提供策略,并且用户可以决定为极端情况等提供自定义策略。如果您提供带有策略的构造函数,则可以通过构造函数注入实现相同的目标-范围。我认为这种实现在许多情况下将提供最大的灵活性。
I'm kind of a beginner when it comes to design patterns. Any thoughts on implementing the strategy pattern/ like this:
public class SomeClass { private Strategy strategy = new DefaultStrategy(); public void provideCustomStrategy(Strategy strategy) { this.strategy = strategy; } }
This will ensure loose coupling and all the other benefits of the Strategy Pattern and DI. At the same time you don't force the user to provide a strategy, and the user can decide to provide a custom strategy for corner cases, etc. One can achieve the same goal with constructor-injection if you provide a constructor with a Strategy-parameter. I think this implementation will provide maximum flexibility in many cases.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这种方法的缺点是您与 DefaultStrategy 类有永久耦合。如果这带来了任何重大的包袱,你将来可能会后悔。
另一种选择可能是使用某种后期绑定。因此,您没有默认策略,而是有默认策略的名称。在运行时,第一次使用时,我们查找名称并加载相应的类。现在我们可以选择通过调整名称-类映射来控制策略。
这是 JEE 在 JNDI 中进行资源查找所实现的一种可能性。
The downside of this approach is that you have a permanent coupling to the DefaultStrategy class. If that brings any significant baggage with it you may regret this in the future.
An alternative might be to use some kind of late-binding. So you don't have a default strategy, instead you have the name of a default strategy. At runtime, on first use, we look up the name a load the corresponding class. Now we have the option of controlling the strategy by adjusting the name-class mapping.
This is one possibility enabled by JEE's resource lookup in JNDI.
我认为要考虑的最重要的事情是,这个实现最适合您的需求吗?我确实同意提供一个设置器(我会将名称更改为 setStrategy),但这样做的一个缺点是客户端需要确切地知道哪些策略可用。向客户端提供该信息的一种方法是通过保存每个可用策略的枚举。然后客户端可以根据需要“热插拔”它们。
您可以在此处查看我的示例代码: www.jasonsjavadocs.com/XHTML/DesignPatterns.html ,在“策略”部分下。
I think the most important thing to consider is, will this implementation best suite your needs? I do agree with providing a setter (I would change the name to setStrategy) but one down side to that is the client will need to know exactly which Strategies are available. One way you can provide that info to the client is through enums that hold each available Strategy. Then the client can "hot swap" them as needed.
You can see my sample code here: www.jasonsjavadocs.com/XHTML/DesignPatterns.html, under the"Strategy" section.