Search code examples
c#strategy-pattern

Implementing the strategy pattern. Do I have to 'new up' everytime?


I am trying to implement the strategy pattern. Here is part of my implementation:

public List<string> GetOrderedEmployeeNames(IOrderByStrategy strategy)
{
   return GetEmployeeFullNames().OrderBy(strategy.Order);
}

now every time I call this function I have to write:

var employees = GetOrderedEmployeeNames(new OrderByFamilyName());

Is 'new-ing up' the strategy every time the right way or am I implementing this incorrectly?


Solution

  • Not necessarily, although it's probably not hurting anything to create objects as I'm assuming they're mostly methods and don't hold a lot of data.

    Some alternatives:

    • Implement a StrategyFactory that either creates new instances or hold references to flyweights (small objects that are indexed by some key, like a string)
    • Implement the strategies as singletons, but that may be more overhead than you need if there are a lot of strategies.