Exercise: Template Method, 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 Template Method Design Pattern.

Getting started

Download the solution to the original exercise MultiValueDictionary.

You may rename the project to TemplateMultiValueDictionary.

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!

Abstract class

Make the class MultiValueDictionary abstract - and rename it to AbstractMultiValueDictionary.

Make an abstract method

  protected abstract ISet<TValue> CreateSet();   

Substitute the line

  values = new HashSet<TValue>()

with the line

  values = CreateSet();  

Now the Add() method is a template method (it calls an abstract method).

Sub class, MultiValueDictionaryHashSet

Make another class, MultiValueDictionaryHashSet. This class must extend AbstractMultiValueDictionary, and implement the abstract method CreateSet().

CreateSet must return a new HashSet<TValue>();

Unit test

Adapt the Unit Test to test the MultiValueDictionaryHashSet class.

Sub class, MultiValueDictionarySortedSet

Make yet another class, MultiValueDictionarySortedSet. This class must extend AbstractMultiValueDictionary, and implement the abstract method CreateSet().

CreateSet must return a new SortedSet<TValue>();

Unit test

Copy the Unit Test class and change it so that it tests the class MultiValueDictionarySortedSet.