How to "subscribe" to events on an object created by a factory in Java?
I currently have a PipeFilterFactory that creates PipeFilter objects. This is how I am using the factory to create some PipeFilter
:
PipeFilterFactory pff = new PipeFilterFactory();
PipeFilter pipeFilter = pff.createPipeFilter();
The problem I am facing is that I have defined an event on PipeFilter
:
public void onOutp开发者_运维技巧ut(int i);
The original idea would be to have it be ran by overriding PipeFilter
's onOutput
, but having the factory create it raises the problem that now I can't seem to do it (I guess the only way to do it is in PipeFilter
's constructor?)
How to solve this?
How about this?
class Me {
PipeFilterFactory pff = new PipeFilterFactory();
PipeFilter pipeFilter = pff.createPipeFilter(
new OutputEventHandler(){
@Override
public void onOutput(int i){
Me.this.tellMe(i);
}
});
}
and
class PipeFilter {
private final OutputEventHandler handler;
//stuff
void onOutput(int i){
if(handler!=null){
handler.onOutput(i);
}
}
}
From what I understand, PipeFilter
must be an abstract or interface in order to make full use of the factory design pattern. Of course, this is not always true.
In genreal, factory design pattern is used to handle the instantiation object, such as what sub type of object to be created, and may also involve setting object properties.
In many case, a factory method is used in conjunction with arguments. You many want to specify the type or condition for which an object of type PipeFilter
to be created.
In your problem here, you might be able to solve your proble by passing integer or condition as argument of factory method, createPipeFilter(int i)
or createPipeFilter(OutputType otype)
.
精彩评论