开发者

Strategy Pattern with default strategy

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 m开发者_开发技巧any cases.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜