这是一个正在尝试的示例程序。
我正在处理物品 - 单件或多件
public interface IItem<T> {
T getContents();
}
/** An item that holds a Map and uses it for something */
public class SingleItem implements IItem<Map<String,String>> {
. . . . .
}
/** An item that holds a List of maps and uses it for something */
public class MultiItem implements IItem<List<Map<String,String>>> {
. . . . .
}
可以生产 SingleItems 或 MultiItems 的生产者
public interface IProducer<T> {
T produce();
}
public class SingleItemProducer implements IProducer<SingleItem> {
@Override
public SingleItem produce() {
return new SingleItem(...);
}
}
public class MultiItemProducer implements IProducer<MultiItem> {
. . . . .
. . . . .
}
可以消费 SingleItems 或 MultiItems 的消费者
public interface IConsumer<T> {
void consume(T item);
}
public class SingleItemConsumer implements IConsumer<SingleItem> {
@Override
public void consume(SingleItem item) {
System.out.println(item.getContents());
}
}
public class MultiItemConsumer implements IConsumer<MultiItem> {
. . . . .
. . . . .
}
将使用生产者和消费者来完成工作的处理器。
public interface IProcessor<T> {
void process();
void process(T item);
}
/** A generic processor that should be able to work with any type of consumer or producer */
public class GenericItemProcessor implements IProcessor<IItem<? extends Object>> {
IProducer<IItem<? extends Object>> producer;
IConsumer<IItem<? extends Object>> consumer;
public GenericItemProcessor (IProducer<IItem<? extends Object>> p, IConsumer<IItem<? extends Object>> c) {
this.producer = p;
this.consumer = c;
}
@Override
public void process() {
IItem<? extends Object> item = null;
// As long the producer produces items, keep processing them
while ((item = producer.produce()) != null) {
this.process(item);
}
}
@Override
public void process(IItem<? extends Object> item) {
consumer.consume(item);
}
}
而且,在主程序中,当我尝试这个时,
IProducer<SingleItem> producer = new SingleItemProducer();
IConsumer<SingleItem> consumer= new SingleItemConsumer();
IProcessor<IItem<? extends Object>> processor = new GenericItemProcessor(producer, consumer);
它说我不能完成最后一个任务。
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The constructor GenericItemProcessor(IProducer<SingleItem>, IConsumer<SingleItem>) is undefined
当然,这会工作,
IProcessor<SingleItem> processor = new GenericItemProcessor(producer, consumer);
IItem<? extends Object>
如果我用SingleItem
inside替换所有出现的GenericItemProcessor
.
但问题是我必须创建一个处理器来处理每种项目类型,这看起来会破坏拥有通用“类型化”处理器的目的。
可能在这里遗漏了一些明显的东西,但是,如何正确地做到这一点?将不胜感激一些建议。