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

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.

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值