Following my previous question, Factory pattern for compile time, apparently, I oversimplified my code example and missed parts of the problem of passing arguments to the Event instance
I am trying to figure out the right design for this problem
I have three classes Thread, Consumer, and Event
public class Thread {
private Consumer _consumer = new Consumer();
}
public class Consumer {
private someMethod() {
Event event = new Event(arg1, arg2);
// do something with event
}
}
In my "main" T is created and its dependencies are encapsulated
Thread t = new Thread();
Now the design has changed and we need multiple Consumer
s and each one of them should construct a different Event
. The code is same for all so I don't need to change Consumer
.
I tried to do it with generics, as it looks like this is a simple and clean way. However, it looks like it is not possible to use new on generic type. (Misguided by C++ templates)
public class Thread<T extends Event> {
private Consumer _c = new Consumer<T>();
}
public class Consumer<T extends Event> {
private someMethod() {
Event event = new T(arg1, arg2);
}
}
My other option is to pass some kind of compile time factory
public interface IEventFactory {
public Event create(Arg1 arg1, Arg2 arg2);
}
public class EventFactory implements IEventFactory{
public Event create(Arg1 arg1, Arg2 arg2) {
return new Event1(arg1, arg2);
}
}
public class Thread {
private Consumer _consumer;
public Thread (IEventFactory _factory) {
_consumer = new Consumer(_factory);
}
}
public class Consumer {
private IEventFactory _factory;
public C(IEventFactory factory) {
_factory = factory;
}
private someMethod() {
Event event = _factory.create(arg1, arg2);
}
}
Is there a better and more elegant way approaching this?
Aucun commentaire:
Enregistrer un commentaire