Pergunta

Let's say I have a channel endpoint where I receive messages. Because I want to process messages in a different way depending on its Header property, rather than create a massive switch I create different strategies with the contract:

interface IMessageHandler
{
    String MessageHeader {get;}
    void Handle(Message msg);
}

So then I can add new handlers for new messages without altering what is already there. But this leaves the door open to have multiple handlers that handle the same message kind. Or with a little change, make a handler able of handling several message kinds:

interface IMessageHandler
{
    Boolean CanHandle(Message msg);
    void Handle(Message msg);
}

But... then it starts to look a lot to the pub/sub pattern, where the message Header property would be the topic to which handlers subscribe...

Where is the line that sepparate both patterns?

Foi útil?

Solução

A canonical Strategy implementation would have a single interface, IStrategy, with multiple implementations, AStrategy and BStrategy. Your application would then request an instance of IStrategy and receive an implementation dependent on the current state of the program. In this way, your IMessageHandler is an instance of the Strategy pattern (although you have encoded the decision of strategy within the interface itself which is where the similarity with Observer begins).

The Observer pattern is similar, but a key part is that you may have any number of observers. If you were to return a list of IMessageHandlers you would be a lot closer to the Observer pattern.

Ultimately the main difference is a semantic one. The Strategy pattern is used to determine how your function should execute; the Observer pattern is used to notify interested parties of an event or message.

Licenciado em: CC-BY-SA com atribuição
scroll top