How to implement one producer , multiple consumers

2019-08-26 09:16发布

问题:

I have a question about Producer/consumer Design pattern , in fact my situation is :I have One class that produce multiple types of messages (notifications) and multiple consumers who consume those messages.

The complication is my Producer produce different types of messages and my consumers consume those messages .

So what is the best implementation of this situation? Is the Producer/Consumer design-pattern the best solution of this situation?

回答1:

I think there are two independent problems here. One is getting a "message" object across. That is a producer/consumer problem, though if you want reliability you need to consider a variety of issues like threading, recovery, etc. If you actually do this between multiple machines, do yourself a favour and use an existing framework like JMS.

Separately from that is the problem of handling different types of messages. Usually you would have some type hierarchy of messages all subtyping a common "Message" ancesor. I'm not sure about the semantics of your message, but something along the lines of the command pattern might be a good fit.

You really need to clarify your question more for us to be able to provide better advice.



回答2:

Given that it sounds like you are coding both the producer and consumer, I would say it would be a good idea to use the produce/consumer pattern. As there are many types of messages, maybe it would be best to use the 'pull' data model (get the consumers to ask for the messages, rather than have every consumer get every message). Here is an outline that may help:

public interface BrokerProducer
{
    public void addConsumer(BrokerConsumer consumer);        
    public void removeConsumer(BrokerConsumer consumer);

    public Price getPrices();
    public Report getReport();
}

public interface BrokerConsumer
{
    public void update(BrokerProducer brokerProducer);
}

public class Broker implements BrokerProducer
{
    private Collection<BrokerConsumer> consumer = new HashSet<BrokerConsumer>();

    // Implement the interface

    // Notify all consumers- there are messages ready.
    public void notifyConsumers()
    {
        for(BrokerConsumer consumer : consumers)
            consumer.update(this);
    }       
}

public class PricesConsumer implements BrokerConsumer
{
    @Override
    public void update(BorkerProducer producer)
    {
        Prices prices = producer.getPrices();
        // Do something with the prices.
    }
}