Vor kurzem war ich auf der Suche nach einer Alternative zum üblichen SwitchCase-Verfahren bei Enumerationen.
Thomas Mentzel hat in seiner “Pattern of the week” Reihe einen sehr schönen anderen Weg über das Strategy Pattern aufgezeigt.
Zuerst hatte ich mich gewundert, denn von einem enum war nichts mehr zu sehen. Er hat Recht, eigentlich braucht man sie nicht.
Eigentlich – was aber wenn doch? Bei StackOverflow bin ich fündig geworden. Hier ist meine eigene Variante der Hochzeit von enum und Strategy Pattern.
namespace EnumMarriesStrategyPattern
{
using SomeOtherComponent;
internal class Program
{
private static void Main()
{
new SomeHandler().ChooseWay(WaysToGo.ThisWay).Go();
// Output: Going this way.
}
}
}
//======================================================================
//======================================================================
namespace SomeOtherComponent
{
using System;
using System.Collections.Generic;
public enum WaysToGo
{
NoWay,
ThisWay,
ThatWay
}
//======================================================================
public class SomeHandler
{
private readonly Dictionary<WaysToGo, IWayToGoStrategy> strategies;
internal SomeHandler()
{
strategies = new Dictionary<WaysToGo, IWayToGoStrategy>
{
{WaysToGo.NoWay, new NoWayStrategy()},
{WaysToGo.ThatWay, new ThatWayStrategy()},
{WaysToGo.ThisWay, new ThisWayStrategy()}
};
}
public IWayToGoStrategy ChooseWay(WaysToGo wayToGo)
{
return strategies[wayToGo];
}
}
//======================================================================
public interface IWayToGoStrategy
{
void Go();
}
internal class NoWayStrategy : IWayToGoStrategy
{
public void Go()
{
throw new NotSupportedException("That's no way to go!");
}
}
internal class ThisWayStrategy : IWayToGoStrategy
{
public void Go()
{
Console.WriteLine("Going this way.");
}
}
internal class ThatWayStrategy : IWayToGoStrategy
{
public void Go()
{
Console.WriteLine("Going that way.");
}
}
}