Strategy Design Pattern

 definition
 UML diagram
 participants
 sample code in C#



definition

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Frequency of use:   medium high

UML class diagram


participants

    The classes and/or objects participating in this pattern are:

  • Strategy  (SortStrategy)
    • declares an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy
  • ConcreteStrategy  (QuickSort, ShellSort, MergeSort)
    • implements the algorithm using the Strategy interface
  • Context  (SortedList)
    • is configured with a ConcreteStrategy object
    • maintains a reference to a Strategy object
    • may define an interface that lets Strategy access its data.

sample code in C#

This structural code demonstrates the Strategy pattern which encapsulates functionality in the form of an object. This allows clients to dynamically change algorithmic strategies.

Show code

// Strategy pattern -- Structural example




This real-world code demonstrates the Strategy pattern which encapsulates sorting algorithms in the form of sorting objects. This allows clients to dynamically change sorting strategies including Quicksort, Shellsort, and Mergesort.

Show code

// Strategy pattern -- Real World example




This .NET optimized code demonstrates the same real-world situation as above but uses modern, built-in .NET features, such as, generics, reflection, object initializers, automatic properties, etc.

Show code

// Strategy pattern -- .NET optimized




Need to know more?

    see what others are saying about the Strategy pattern





  • Better Code
  • Better Career
  • Better Lifestyle


Design Pattern
FrameworkTM 3.5


 
C# and VB.NET


     Here's what you get:
  • Gang of Four Patterns
  • Head First Patterns
  • Enterprise Patterns
  • SOA Patterns

  • WPF Best Practices
  • WCF Best Practices
  • LINQ Best Practices

  • Model View Controller
  • Model View Presenter
  • Model View ViewModel

  • More...

Click here for details

-- Instant Access --
Instant Download