Exercise: Strategy, MultiValueDictionary

In a previous exercise you programmed a class MultiValueDictionary.

In the solution to the previous exercise elements are kept in a HashSet<TValue>.

In this exercise you must make the solution more flexible, so that we can use different kinds of ISet<TValue> implementations (like HashSet<T> and SortedSet<T>) to keep the elements.

To obtain this you must use the Strategy Design Pattern. Using the Strategy Design Patterns you will be able to change strategy even when the program in running.

Getting started

Download the solution to the original exercise MultiValueDictionary.

You may rename the project to StrategyMultiValueDictionary.

In the Add method locate the line

  values = new HashSet<TValue>();

This is where we decide to use a HashSet. This is were we want more flexibility!

Property

Add another property to the class MultiValueDictionary.

  public Func<ISet<TValue>> ValuesCollectionFactory { get; set; }  

Func<ISet<TValue>> i a delegate type: Functions with no parameter returning an ISet<TValue> object.

Constructor: Initialize the property

The constructor of MultiValueDictionary must initialize the property ValuesCollectionFactory.

The constructor must have a parameter of type Func<ISet<TValue>>.

Add: Use the property

In the Add method get rid of new HashSet... and use the property to obtain a new ISet<TValue> object.

Run the Unit test to check that nothing is broken.

Extra: Property: Default value

Add an no-argument constructor. This constructor should initialize the ValuesCollectionFactory using a default strategy.

The default strategy can be made as a static readonly field.