Hallo Community,
mein Artikel über die Verbindung von Enumerationen und Dictionaries zu einer Variante des Strategy Patterns hat mich irgendwie nicht mehr losgelassen. Ich habe mich gefragt, ob man mit diesem Verfahren auch direkt Methoden aufrufen kann. Somit würde ich mir den Overhead verschiedener Strategy-Klassen einsparen.
Und tatsächlich, es geht!
using System;
using System.Collections.Generic;
namespace DictionariesFunctional
{
public enum Method
{
ThisMethodTakesString,
ThatMethodReturnsString
}
public class Sut
{
public Sut()
{
MethodRepository = new Dictionary<Method, Delegate>();
MethodRepository.Add(Method.ThisMethodTakesString,
new Action<string>(ThisMethodTakesString));
MethodRepository.Add(Method.ThatMethodReturnsString,
new Func<string>(ThatMethodReturnsString));
}
public Dictionary<Method, Delegate> MethodRepository
{ get; private set; }
public string Result { get; private set; }
private void ThisMethodTakesString(string s)
{
Console.WriteLine("This method echoes " + s + ".");
Result = s;
}
private string ThatMethodReturnsString()
{
return "Hello from that method";
}
}
}
Dazu noch ein paar Tests:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SharpTestsEx;
namespace DictionariesFunctional
{
// ReSharper disable InconsistentNaming
[TestClass]
public class UnitTest1
{
[TestMethod]
public void Should_call_ThisMethodTakesString()
{
var sut = new Sut();
sut.MethodRepository[Method.ThisMethodTakesString]
.DynamicInvoke("Hello world");
sut.Result.Should().Be("Hello world");
}
[TestMethod]
public void Should_call_ThatMethodReturnsString()
{
var sut = new Sut();
var actual = sut.MethodRepository[Method.ThatMethodReturnsString]
.DynamicInvoke();
actual.Should().Be("Hello from that method");
}
}
}
Jetzt fragt sich nur noch, ob und wofür das in der Praxis zu gebrauchen ist. Was meint ihr?