I found a very useful purpose for the strategy pattern. I am writing an application that will move all or part of a database depending on the users selection. Since 90% of the code was the same I decided to use an abstract class with concrete methods for the business logic that was the same and abstract classes for where it differed. The strategies I have to choose from are:
1. Move entire DB
2. Move all rows from X number of tables.
3. Move X number of rows from X tables.
Doing a quick mock I came up with
public abstract class DBMoveStrategy
{
//properties...
//events...
//concrete methods
public abstract void GetSource();
public abstract void AddConstraints(DataSetFacade Data);
}
Then I sub-class for the different branches of logic.
public class DBMoveAll : DBMoveStrategy
{
public override void GetSource()
{
//some code
}
public override void AddConstraints(DataSetFacade Data)
{
//some code
}
}
public class DBTables : DBMoveStrategy
{
public override void GetSource()
{
//some code
}
public override void AddConstraints(DataSetFacade Data)
{
//some code
}
}
public class DBMoveRows : DBMoveStrategy
{
public override void GetSource()
{
//some code
}
public override void AddConstraints(DataSetFacade Data)
{
//some code
}
}
To use this inside another class I just do the following:
public class MyControllerClass
{
private DBMoveStrategy movedb;
public MyControllerClass()
{
if (IsMoveAll)
movedb = new DBMoveAll();
}
public void Connect(string Server, string Database, string UserName, string Password)
{
movedb.connect(string Server, string Database, string UserName, string Password)
}
public void GetData()
{
movedb.GetSource();
movedb.AddConstraints();
}
}
There is more logic involved but this will give a flavor for how I am using the pattern. There are probably some better ways I could use it or other patterns that might be better but I am still learning the language and better ways to write code.
Friday, September 19, 2008
Subscribe to:
Post Comments (Atom)
1 comment:
That's pretty tight. We gotta discuss sometime.
Post a Comment