Question

Currently, I have a standard strategy pattern implementation,simplified:

public interface IStrategy
{
    IList<Dog> GetDogs();

}

public class DogStrategy: IStrategy
{
    public IList<Dog> GetDogs()
    {
       return new List<Dog>();
    }
}

I also have a a class that uses a strategy:

public class DogCollection
{
    private IStrategy strategy;
    public IStrategy Strategy
    {
        get { return strategy; }
        set
        {
            if (strategy == null || value.GetType() != strategy.GetType())
            {
                strategy = value;
                //do stuff
            }
        }
  }

Problem: what I've discovered having implemented the pattern in 2 places is the interfaces are starting to proliferate a bit. This is manageable and flexible but I know colleagues will get upset by having too many files - they don't like design patterns. Also I need to use some logic common to the strategies so the collection needs to have an abstract class it inherits from.

I was thinking instead of using all of these interfaces to let DogCollection inherit from a Generic Collection containing the extra logic:

public class DogCollection : GenericCollection<Dog>

I could use a Loader property rather than an IStrategy property. I could then delete various files for both strategy patterns:

public abstract class GenericCollection<T> 
{
    private Func<IList<T>> loader;
    public Func<IList<T>> Loader
    {
        get { return loader; }
        set 
        {
            loader = value; 
            //do stuff
        }
    }
}

Instead of setting the strategy by instatitiating concrete strategy implementations on various conditions and setting the strategy in the DogCollection, I would simply create a static class containing routines to get different Dogs and assign the Loader Property. The loader property could then be used to return the list when it is requested.

Which is preferred and why?

Was it helpful?

Solution

This is still the strategy pattern.

Note that design patterns are often used to overcome shortcomings in the programming language you use.

In C# functions are nearly so-called first class citizens by using delegate types and there's actually no need to wrap your strategy into an interface and a class.

The effect is basically the same and I would prefer the second approach using the Func<> delegate: less code, less interfaces, less classes, less files, less confusion.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top