Real World Example of the Strategy Pattern

I've been reading about the OCP principle and how to use the strategy pattern to accomplish this.

I was going to try and explain this to a couple of people, but the only example I can think of is using different validation classes based on what status an "order" is.

I've read a couple of articles online, but these don't usually describe a real alike reason to use the strategy, like generating reports/bills/validation, etc...

Are there any real-world examples where you think a strategy pattern is common?


What about this:

You have to encrypt a file.

For small files, you can use "in memory" strategy, where the complete file is read and kept in memory ( let's say for files < 1 gb )

For large files, you can use another strategy, where parts of the file are read in memory and partial encrypted results are stored in tmp files.

These may be two different strategies for the same task.

The client code would look the same:

 File file = getFile();
 Cipher c = CipherFactory.getCipher( file.size() );
 c.performAction();



// implementations:
interface  Cipher  {
     public void performAction();
}

class InMemoryCipherStrategy implements Cipher { 
         public void performAction() {
             // load in byte[] ....
         }
}

class SwaptToDiskCipher implements Cipher { 
         public void performAction() {
             // swapt partial results to file.
         }

}

The

     Cipher c = CipherFactory.getCipher( file.size() );

Would return the correct strategy instance for the cipher.

I hope this helps.

( I don't even know if Cipher is the right word :P )


Again, an old post but still turns up on searches so I'll add two more examples (Code is in C#). I absolutely love the Strategy pattern since it has saved my butt a lot of times when the project managers say: "We want the application to do 'X', but 'X' is not yet clear and it can change in the near future." This video explaining the strategy pattern, uses StarCraft as an example.

Stuff that falls in this category:

  • Sorting: We want to sort these numbers, but we don't know if we are gonna use BrickSort, BubbleSort or some other sorting

  • Validation: We need to check items according to "Some rule", but it's not yet clear what that rule will be, and we may think of new ones.

  • Games: We want player to either walk or run when he moves, but maybe in the future, he should also be able to swim, fly, teleport, burrow underground, etc.

  • Storing information: We want the application to store information to the Database, but later it may need to be able to save a file, or make a webcall

  • Outputting: We need to output X as a plain string, but later may be a CSV, XML, JSON, etc.


Examples

I have a project where the users can assign products to people in a database. This assignment of a product to a person has a status which is either "Approved" or "Declined", which is dependent on some business rules. For example: if a user assigns a product to a person with a certain age, it's status should be declined; If the difference between two fields in the item is larger than 50, it's status is declined, etc.

Now, at the moment of development these business rules are not yet all completely clear, and new rules could come up at any time. The power of the stragety-pattern is that I made a RuleAgent, which is given a list of IRules.

public interface IRule {
    bool IsApproved(Assignment assignment); 
 }

At the moment of assigning a product to a person, I create a RuleAgent, give it a list of rules (which all implement IRule), and ask it to validate an assignment. It'll run through all it's rules. Which, because they all implement the same interface, all have the IsApproved method and return false if any of them returns false.

Now when for instance the manager suddenly comes up and says, we also need to decline all assignments to interns, or all assignments to people working overtime... You make new classes like this:

public OvertimeRule : IRule
{
    public bool IsApproved(Assignment assignment) //Interface method
    {
        if (assignment.Person.Timesheet >= 40)
        {
            return false;
        }
        return true;
    }
}

public InternRule : IRule
{
    public bool IsApproved(Assignment assignment) //Interface method
    {
        if (assignment.Person.Title == "Intern")
        {
            return false;
        }
        return true;
    }
}

You see that you don't have to keep adding or removing if-statements or code, just make a new rule-class that implements the IRUle interface and switch those out when needed.


Another great example: Scott Allen's video series at http://www.asp.net/mvc/pluralsight where he uses the strategy pattern in the Unit-test part of the application

He builds a website which has a page that displays items based on popularity. However "Popular" can be many things (most views, most subscribers, creation date, most activity, least amount of comments, etc), and in case management doesn't yet know exactly how to order, and may want to experiment with different orderings at a later date. You make an interface (IOrderAlgorithm or something) with an order method, and let an Orderer-object delegate the ordering to a concrete implementation of the IOrderAlgorithm interface. You can make a "CommentOrderer", "ActivityOrderer", etc... And just switch these out when new requirements come up.


Key notes:

  1. Strategy is behavioral design pattern. It is used to switch between family of algorithms.

  2. This pattern contains one abstract strategy interface and many concrete strategy implementations (algorithms) of that interface.

  3. The application uses strategy interface only. Depending on some configuration parameter, the concrete strategy will be tagged to interface.

UML Diagram from wikipedia

enter image description here

One real word example : Airlines offering discounts during some months (July-December). You can have one Fare module, which decides pricing options depending on month number.

Have a look at a simple example. This example can be extended to on-line retailing applications, which provides discount to shopping cart items on special days/happy hours easily.

import java.util.*;

/* Interface for Strategy */
interface OfferStrategy {
    public String getName();
    public double getDiscountPercentage();
}
/* Concrete implementation of base Strategy */
class NoDiscountStrategy implements OfferStrategy{
    public String getName(){
        return this.getClass().getName();
    }
    public double getDiscountPercentage(){
        return 0;
    }
}
/* Concrete implementation of base Strategy */
class QuarterDiscountStrategy implements OfferStrategy{
    public String getName(){
        return this.getClass().getName();
    }
    public double getDiscountPercentage(){
        return 0.25;
    }
}
/* Context is optional. But if it is present, it acts as single point of contact
   for client. 

   Multiple uses of Context
   1. It can populate data to execute an operation of strategy
   2. It can take independent decision on Strategy creation. 
   3. In absence of Context, client should be aware of concrete strategies. Context acts a wrapper and hides internals
   4. Code re-factoring will become easy
*/
class StrategyContext {
    double price; // price for some item or air ticket etc.
    Map<String,OfferStrategy> strategyContext = new HashMap<String,OfferStrategy>();
    StrategyContext(double price){
        this.price= price;
        strategyContext.put(NoDiscountStrategy.class.getName(),new NoDiscountStrategy());
        strategyContext.put(QuarterDiscountStrategy.class.getName(),new QuarterDiscountStrategy());        
    }
    public void applyStrategy(OfferStrategy strategy){
        /* 
        Currently applyStrategy has simple implementation. You can use Context for populating some more information,
        which is required to call a particular operation            
        */
        System.out.println("Price before offer :"+price);
        double finalPrice = price - (price*strategy.getDiscountPercentage());
        System.out.println("Price after offer:"+finalPrice);
    }
    public OfferStrategy getStrategy(int monthNo){
        /*
            In absence of this Context method, client has to import relevant concrete Strategies everywhere.
            Context acts as single point of contact for the Client to get relevant Strategy
        */
        if ( monthNo < 6 )  {
            return strategyContext.get(NoDiscountStrategy.class.getName());
        }else{
            return strategyContext.get(QuarterDiscountStrategy.class.getName());
        }

    }
}
public class StrategyDemo{    
    public static void main(String args[]){
        StrategyContext context = new StrategyContext(100);
        System.out.println("Enter month number between 1 and 12");
        int month = Integer.parseInt(args[0]);
        System.out.println("Month ="+month);
        OfferStrategy strategy = context.getStrategy(month);
        context.applyStrategy(strategy);
    }

}

output:

Enter month number between 1 and 12
Month =1
Price before offer :100.0
Price after offer:100.0

Enter month number between 1 and 12
Month =7
Price before offer :100.0
Price after offer:75.0

Useful articles:

strategy pattern by dzone

strategy pattern by sourcemaking


I can think of several fairly simple examples:

  • Sorting a list. The strategy is the comparison used to decide which of two items in the list is "First"
  • You might have an application where the sorting algorithm itself (QuickSort, HeapSort, etc.) may be chosen at runtime
  • Appenders, Layouts, and Filters in Log4Net and Log4j
  • Layout Managers in UI toolkits
  • Data compression. You might have an ICompressor interface whose sole method looks something like this:

    byte[] compress(byte[] input);

    Your concrete compression classes might be things like RunLengthCompression, DeflateCompression, etc.