xtadex
xtadex

Reputation: 116

What design pattern correspond to described solution

The solution below very similar to the "handlers" concept, but still struggling to find correspondent pattern or (combination of patterns). Instead of words will try to describe through the simple C# code:

interface IHandler
{
    bool CanHandle(string requestType);
    void Handle(object request);
}

IHandler[] handlers = new IHandler[] {h1, h2, ...., hN};

void Handle(string requestType, object request)
{
    foreach(var handler in handlers)
    {
        if(handler.CanHandle(requestType)) 
        {
            handler.Handle(request);

            return;
        }
    }
}

What I want to emphasize here: request object passed to only one or zero handlers. Doing that way I want to make sure that other handlers will not corrupt the state of request.

PS. Another option is to refactor that code into a more pattern-oriented solution.

Upvotes: 0

Views: 100

Answers (1)

Matt Timmermans
Matt Timmermans

Reputation: 59253

You're probably making a mistake in thinking that a handler should be able to decide whether or not it can handle a request based solely on the requestType string.

If it is your intent to give the early handlers a chance to decide how the request is handled before considering the later handlers, consider switching to a more standard chain of responsibility pattern. It does that without presuming to know how each handler will make its decision.

If you really expect the handling decision to be based solely on requestType, then you should build a Map<String, IHandler> during initialization, and then just look up the correct handler instead of walking a chain for every request.

Upvotes: 2

Related Questions