February 10, 2011 by Christoff Truter C# Design Patterns Architecture
The strategy design pattern defines a means by which we decouple a family of related
algorithms and make them interchangeable among one another within a required context.
The interchangeable bits are referred to as strategies, generally one would define a strategy
by way of interface or abstract class e.g.
interface IStrategy
{
bool DoSomething();
}
/*
abstract class Strategy
{
abstract public bool DoSomething();
}
*/
class StrategyA : IStrategy
{
public bool DoSomething()
{
return true;
}
}
class StrategyB : IStrategy
{
public bool DoSomething()
{
return true;
}
}
class Context
{
private IStrategy _Strategy;
public Context(IStrategy Strategy)
{
this._Strategy = Strategy;
}
public bool DoSomething()
{
return this._Strategy.DoSomething();
}
}
class Program
{
static void Main(string[] args)
{
Context ctx = ((args.Length > 0) && (args[0] == "a"))
? new Context(new StrategyA())
: new Context(new StrategyB());
ctx.DoSomething();
}
}
interface IStrategy
{
public void UploadFile(String fullname, String folder);
}
class FTPStrategy : IStrategy
{
public void UploadFile(string fullname, string folder)
{
FileInfo fileInfo = new FileInfo(fullname);
Uri requestUri = new Uri(String.Concat("ftp://example.com", folder, "/", fileInfo.Name));
FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(requestUri);
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpRequest.Credentials = new NetworkCredential("username", "password");
using (Stream writer = ftpRequest.GetRequestStream())
{
byte[] contents = File.ReadAllBytes(fullname);
writer.Write(contents, 0, contents.Length);
}
}
}
class LocalStrategy : IStrategy
{
public void UploadFile(string fullname, string folder)
{
FileInfo fileInfo = new FileInfo(fullname);
byte[] contents = File.ReadAllBytes(fullname);
File.WriteAllBytes(String.Concat("c:", folder, "/", fileInfo.Name), contents);
}
}
class Context
{
private IStrategy _Strategy;
public Context(Strategies strategy)
{
if (strategy == Strategies.FTP)
{
_Strategy = new FTPStrategy();
}
else if (strategy == Strategies.Local)
{
_Strategy = new LocalStrategy();
}
}
public void UploadFile(string fullname, string folder)
{
this._Strategy.UploadFile(fullname, folder);
}
}
enum Strategies
{
FTP,
Local
}
class Program
{
static void Main(string[] args)
{
Context ctx = new Context(Strategies.FTP);
ctx.UploadFile(@"c:\somefolder\xls.xml", "/Skool");
}
}