Search This Blog

Tuesday, August 10, 2010

Strategy pattern

Strategy pattern (also known as the policy pattern) is a particular software design pattern, whereby algorithms can be selected at runtime. The essential requirement in the programming language is the ability to store a reference to some code in a data structure and retrieve it. This can be achieved by mechanisms such as the native function pointer, the first-class function, classes or class instances in object oriented programming languages, or accessing the language implementation's internal storage of code via reflection. Delegates in C# follow the strategy pattern, where the delegate definition defines the strategy interface and the delegate instance represents the concrete strategy. .NET 3.5 defines the Func<,> delegate which can be used to quickly implement the strategy pattern. You can use this delegate to represent a method that can be passed as a parameter without explicitly declaring a custom delegate. By using anonymous methods, you reduce the coding overhead in instantiating delegates because you do not have to create a separate method.

The UML class diagram for the Strategy pattern is the same as the diagram for the Bridge pattern. However, these two design patterns aren't the same in their intent. While the Strategy pattern is meant for behavior, the Bridge pattern is meant for structure.

The coupling between the context and the strategies is tighter than the coupling between the abstraction and the implementation in the Bridge pattern.

No comments: