Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the "Dispatcher" design pattern?

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.

like image 592
Ben Farmer Avatar asked Mar 17 '10 20:03

Ben Farmer


People also ask

What is a Dispatcher?

A Dispatcher is a professional who ensures that everything runs smoothly by coordinating with customers, providing precise logistics for drivers to follow along on their routes, and coordinating delivery times. Dispatchers are the point of contact for drivers and have all the information needed to make deliveries.

What is controller design pattern?

The front controller design pattern means that all requests that come for a resource in an application will be handled by a single handler and then dispatched to the appropriate handler for that type of request. The front controller may use other helpers to achieve the dispatching mechanism.

What is a message Dispatcher?

It allows multiple consumers on a single channel to coordinate their message processing.


1 Answers

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

like image 83
stmax Avatar answered Sep 21 '22 09:09

stmax