The pattern states: Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. Look at the below example demonstrating a potential problem:
Class: Logger
1 2 3 4 5 6 7 8 9 10 | namespace Strategy { public class Logger { public void Log(string logMessage) { Console.WriteLine(logMessage); } } } |
Interface: ILogHandler
1 2 3 4 5 6 7 | namespace Strategy { public interface ILogHandler { void Log(string logMessage); } } |
Class: Logger
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | namespace Strategy { public class Logger { private ILogHandler _LogHandler; public void SetLogHandler(ILogHandler logHandler) { _LogHandler = logHandler; } public void Log(string logMessage) { if (_LogHandler != null) { _LogHandler.Log(logMessage); } } } } |
Class: ConsoleLogger : ILogHandler
1 2 3 4 5 6 7 8 9 10 | namespace Strategy { public class ConsoleLogger : ILogHandler { public void Log(string logMessage) { Console.WriteLine(logMessage); } } } |
Class: FileLogger : ILogHandler
1 2 3 4 5 6 7 8 9 10 | namespace Strategy { public class FileLogger : ILogHandler { public void Log(string logMessage) { // Log to file functionality } } } |
http://www.dofactory.com/Patterns/PatternStrategy.aspx
http://patnys.com/archive/2008/04/15/strategy-pattern.aspx
No comments:
Post a Comment