Strategy pattern
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   jason_eastwood
Posted On:   Tuesday, December 10, 2002 10:19 PM

Could someone show me an example of how the Strategy pattern eliminates conditional statements. Suppose I have a client class that needs to choose which strategy to implement based on some value. I end up with code like this: Context context = new Context(); if ( value.equals( "somevalue" ) ) { context.changeStrategy( new MyStrategy() ); } else if ( value.equals( "someOtherValue" ) ) { context.changeStrategy( new otherStrategy() ); } context.evaluateAlgorithm(); That's all well and good ..but I'm missing something, because the conditional statements haven't been eliminated from this clie   More>>

Could someone show me an example of how the Strategy pattern eliminates conditional statements. Suppose I have
a client class that needs to choose which strategy to implement based on some value. I end up with code like this:




			
Context context = new Context();
if ( value.equals( "somevalue" ) )
{
context.changeStrategy( new MyStrategy() );
}
else if ( value.equals( "someOtherValue" ) )
{
context.changeStrategy( new otherStrategy() );
}

context.evaluateAlgorithm();






That's all well and good ..but I'm missing something, because the conditional statements haven't been eliminated from this client code. Any insight would be greatly appreciated !    <<Less

Re: Strategy pattern

Posted By:   Anonymous  
Posted On:   Thursday, December 12, 2002 12:47 AM

First, if you use the strategy at different locations, you have replaced several scattered conditional statements by one single one.

Second, you could even remove this single conditional statement:


Map strategyMapping = new HashMap();
strategyMapping.put("someValue", new SomeStrategy());
strategyMapping.put("otherValue", new OtherStrategy());
...
Context context = new Context();
context.changeStrategy(strategyMapping.get(value));
context.evaluateAlgorithm();

Re: Strategy pattern

Posted By:   Lasse_Koskela  
Posted On:   Wednesday, December 11, 2002 12:12 AM

Well, think of the situation where you don't have separate strategies but one big pile of logic... Then you've got a lot more if-else statements. And of course you can use a map structure instead of if-else in the client code.
About | Sitemap | Contact