java 多个消费者,如何在Java中实现一个生产者,多个消费者和多个对象?

2023-05-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?

解决方案

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 consumer = new HashSet();

// 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.

}

}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

java 多个消费者,如何在Java中实现一个生产者,多个消费者和多个对象? 的相关文章

随机推荐