views:

233

answers:

1

What is the "dispatcher" pattern and how would I implement it in code?

I have a property bag of generic objects and would like to have the retrieval delegated to a generic method.

Currently, I have properties looking for a specific key in the bag. For example:

private Dictionary<String, Object> Foo { get; set; }
private const String WidgetKey = "WIDGETKEY";

public Widget? WidgetItem
{
    get
    {
        return Foo.ContainsKey(WidgetKey) ? Foo[WidgetKey] as Widget: null;
    }
    set
    {
        if (Foo.ContainsKey(WidgetKey))
            Foo[WidgetKey] = value;
        else
            Foo.Add(WidgetKey, value);
    }
}

It was suggested that this could be more generic with the "dispatcher" pattern, but I've been unable to find a good description or example.

I'm looking for a more generic way to handle the property bag store/retrieve.

+1  A: 

I'm not sure I understand your question correctly, but...

I have a property bag of generic objects and would like to have the retrieval delegated to a generic method.

... sounds like you're looking for information on "double-dispatching"?

Imagine you have three classes:

abstract class A {}
class B extends A {}
class C extends A {}

And two methods to do something with objects of type B and C:

void DoSomething(B obj) {}
void DoSomething(C obj) {}

The problem is that when all you have is a variable of static type A...:

A a = new B();

... you cannot call DoSomething(a) because at compile time only its static type (A) is known, so the compiler cannot decide if it should call method DoSomething(B obj) or DoSomething(C obj).

This is where double dispatching comes in. Some languages support it out of the box, others like C++, C# and Java don't. But you can implement it yourself in these languages as well. For an example see:

http://en.wikipedia.org/wiki/Double_dispatch

And:

http://en.wikipedia.org/wiki/Visitor_pattern

stmax