Reputation: 33
A lot of search coudnt help me with my problem. While refactoring a lot of code, which realize Producer-Consumer pattern, i get a problem with a simple composition.
By the end of refactoring we have a very simple structure
1) A class Spooler, that shedules Consumer threads.
2) An abstract class AbstractConsumer, that contains some real methods and variables and one abstract method run();
3) Subclasses - real Consumers, that extend AbstractConsumer and override run() method.
class Spooler {
private int spoolSize = 100;
private Consumer[] spool = null;
//private ArrayList<? extends Consumer> spool = null;
//...
public Spooler() {
init();
}
public final void init() {
if (spool == null) {
spool = new ArrayList<Consumer>();
for (int i = 0; i < spool.size(); i++) {
spool.add(new Consumer(null, null));
spool[i] = new Consumer();
spool[i].start();
}
}
}
}
public abstract class AbstractConsumer extends Thread {
//some NOT ABSTRACT variables and methods
@Override
public abstract void run();
}
class XmlConsumer extends Consumer {
@Override
public void run() {
//consume current task
}
}
So, what i want. When i need some multithreading dataprocessing, i realize current Consumer, override run() method of abstract superclass. Realize new Spooler, which constructor have to get the currentConsumer. And then all it have to work, i think.
I don't know how to add AbstractConsumer into Spoolers ArrayList without implementation its abstract methods. Like that
for (int i = 0; i < spool.size(); i++) {
spool.add(new AbstractConsumer() {
@Override
public void run() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
})
}
I think, its need to use Java Generics Classes here, i tried hard, but all fails. Please tell me how can i solve my problem. Thank you =)
Upvotes: 2
Views: 95
Reputation: 279
if you want your spooler to be generic, you should compose it with a factory that you inject in the constructor of the spooler
interface ConsummerFactory {
public AbstractConsummer create();
}
so in the init
method of your spooler, you invoke the create
method of the factory
then if you want a spooler of XmlConsumer
you just need to implement a ConsummerFactory
whose create
method create a XmlConsummer
and give it as argument of the constructor of your spooler
Upvotes: 1