Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

c# - Use factory pattern with single and multiple returns

I have a factory pattern implemented for handling several messages which derive from the class MessageBase (e.g. StartMessage, etc).

To handle these messages, I have different handlers that derive from IMessageHandler:

public interface IMessageHandler
{
      MessageHandleResult HandleMessage(MessageBase message);
}

public class StartMessageHandler: IMessageHandler
{
      public MessageHandleResult IMessageHandler.HandleMessage(MessageBase message)
      {
         ...
      }
}

To retrieve the handlers, it is quite simple:

var messagehandler = MessageHandlerFactory.GetMessageHandlerFor(message);
var result = messagehandler.HandleMessage(message);

But in the new situation, I have to handle a new type of message (which also neatly derives from MessageBase). The messagehandler for this new message must return the result as a list of messageresults:

public class NewMessageHandler: IMessageHandler
{
      public List<MessageHandleResult> IMessageHandler.HandleMessage(MessageBase message)
      {
         ...
      }
}

Any ideas on how to refactor this in a correct way. The solution was working perfectly for 6 types of messages until this new message type was introduced.

question from:https://stackoverflow.com/questions/65862209/use-factory-pattern-with-single-and-multiple-returns

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Change the interface to:

public interface IMessageHandler
{
      IEnumerable<MessageHandleResult> HandleMessage(MessageBase message);
}

This would enable you to dispense with the MessageHandlerFactory.GetMessageHandlerFor step, which is a design smell anyway.

Instead, you can simply pass a message to a list of message handlers and concatenate the results:

var results = messagehandlers.SelectMany(h => h.HandleMessage(message));

Message handlers that don't handle a particular subtype of MessageBase can return an empty list.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...