In our project we often choose algorithm by some conditions.
For example, suppose we need to print order for different products. We need to choose different blanks and retrieve different data according to product type, price or any other product characteristic. Usually, we write something like this.
public interface IOrderPrinter
{
bool CanPrint(Order order);
PrintResult Print(Order order);
}
class CompositeOrderPrinter : IOrderPrinter
{
private IList<IOrderPrinter> printers;
public bool CanPrint(Order order)
{
return printers.Any(p => p.CanPrint(order));
}
public PrintResult Print(Order order)
{
foreach (var printer in printers)
{
if (printer.CanPrint(order))
return printer.Print(order);
}
// throw some exception
}
public void AddPrinter(IOrderPrinter printer)
{
printers.Add(printer);
}
}
class FirstOrderPrinter : IOrderPrinter
{
public bool CanPrint(Order order)
{
return order.ProductType == ProductType.Banana && order.Price < 100;
}
public PrintResult Print(Order order)
{
if (!CanPrint)
// throw some exception
// print ...
}
}
class SecondOrderPrinter : IOrderPrinter
{
public bool CanPrint(Order order)
{
return order.ProductType == ProductType.Apple;
}
public PrintResult Print(Order order)
{
if (!CanPrint)
// throw some exception
// print ...
}
}
Does this pattern have any commonly known name? Yes, it’s look pretty similar as Composite pattern, but there are differences anyway. Is there any standard design pattern which solves this task in better (more elegant, less code, …) way? It’ll be interesting to read about another ways to implement similar behavior.
When you choose an algorithm at runtime, it’s called the Strategy Pattern.