Pierre Greborio.NET

Talking about .NET world

Strategy vs Policy pattern

The strategy pattern encapsulates an algorithm inside a class in order to make them interchangable. For example consider we have to round a monetary value to the nearest smallest currency. We could define an interface:

public interface RoundingStrategy
{
  double Round(double amount);
}

and then several strategy algorithms, such as:

public class EurRoundingStrategy : RoundingStrategy
{
  public double Round(double amount)
  {
    // Implementation here
  }
}

and

public class UsdRoundingStrategy : RoundingStrategy
{
  public double Round(double amount)
  {
    // Implementation here
  }
}

But generally, this isn't enought. We have to add other methods that round not only to the smallest currency but also to a user/law/business defined amount, then we can use the policy pattern (a generalization to the strategy pattern) adding new methods:

public interface RoundingStrategy
{
  double Round(double amount);
  double Round(double amount, double precision);
}

Comments

fx brokers said:

Theme: Day Dream by Jim Whimpey. Blog at WordPress. com.

# August 23, 2008 11:35 PM