如何在Java中实现一个生产者,多个消费者和多个对象? [英] How to implement one producer , multiple consumers and multiple Objects in Java?

查看:816
本文介绍了如何在Java中实现一个生产者,多个消费者和多个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于生产者/消费者设计模式的问题,实际上我的情况是:我有一个类可以生成多种类型的消息(通知)和消费这些消息的多个消费者。



复制是我的生产者产生不同类型的消息,我的消费者消费这些消息。



那么这种情况最好的实现是什么?生产者/消费者设计模式是这种情况的最佳解决方案吗?

解决方案

鉴于这听起来像是编码生产者和消费者,我会说使用生产/消费者模式是一个好主意。由于有许多类型的消息,也许最好使用拉数据模型(让消费者要求消息,而不是让每个消费者获得每个消息)。这是一个可能有帮助的大纲:

  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实现BrokerProducer
{
private Collection&BrokerConsumer> consumer = new HashSet&BrokerConsumer>();

//实现界面

//通知所有消费者 - 有准备好的消息。
public void notifyConsumers()
{
(BrokerConsumer consumer:consumer)
consumer.update(this);
}
}

public class PricesConsumer实现BrokerConsumer
{
@Override
public void update(BorkerProducer producer)
{
价格= producer.getPrices();
//用价格做某事。
}
}


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

这篇关于如何在Java中实现一个生产者,多个消费者和多个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆