Home  /  Questions  /  Question

65   95.8
Aug 09, 2010

Sample VB.NET code for a Strategy Pattern for algorithms


I'm using the Heads Up Patterns book for getting into Design Patterns.  The book uses a Duck to illustrate the Strategy pattern. Could this be the reason why people think Strategy looks like a Factory Pattern? 

According to posts here the Strategy Pattern is more for 'plugging in' different algorithms.  Does anyone know where I can get a VB code sample that uses this pattern for different algorithms? 


 1 comment
Not sure about the ducks :) But Factory is a creational pattern meaning it is used for creating objects. Whereas Strategy is a behavior pattern meaning it is used to change behavior on existing objects. --- Robert Blixt  Aug 13, 2010

1,128   99.9
Aug 13, 2010
I have a link to a C# implementation version of the strategy pattern here.
If you're uncomfortable reading C# try using a C#->VB converter.

Of course, you can take a look at the design pattern framework for VB.Net
which has implementations of the Strategy pattern for VB.Net.

555   99.9
Aug 13, 2010
I recently introduced the strategy pattern in my team as a way of replacing a Select-Case conditional statement so that an existing implementation of a class doesn't need to be changed when another case needs to be added.

This basically works like this:
I have an abstract (strategy-) class declaring an algorithm method that needs to be overridden. From this class, I inherit concrete implementations that use different algorithms. A context class is able to route requests to the respective concrete implementation. This way I can fork from a given condition to the corresponding case-clause (i.e. the concrete algorithm) by using only one call to the context class.

When a new case is introduced I simply add another concrete strategy class and thats basically it.

EDIT: I posted a question here that was also about that topic. The website I got the first implementation from is this one: http://blogs.microsoft.co.il/blogs/gilf/archive/2009/11/22/applying-strategy-pattern-instead-of-using-switch-statements.aspx