Reputation: 3
I am trying to implement a factory pattern where the method returns me back the correct object. When making the call to the factory method my private constructor is getting called and this causes repercussions in the result of that class.
I put the print statement into the constructor to see if it is called and it results in a call regardless of what Strings are provided to the factory.
public class ExcerptFilter implements TokenFilter
{
private boolean started;
private ExcerptFilter() {
start();
System.out.println("constructor called");
}
public static TokenFilter factory(String startTag, String stopTag) {
TokenFilter result;
if(startTag != null && startTag.trim().length() > 0){
if(stopTag != null && stopTag.trim().length() > 0) result = new ExcerptFilterStartAndStop(startTag, stopTag);
else result = new ExcerptFilterStartOnly(startTag);
}else{
if(stopTag != null && stopTag.trim().length() > 0) result = new ExcerptFilterStopOnly(stopTag);
else result = new ExcerptFilter();
}
return result;
}
The factory should return the correct instance of a nested class in ExcerptFilter. It shouldn't make any calls to the constructor UNLESS the who parameters to factory() are zero length or null.
Upvotes: 0
Views: 300
Reputation: 285401
Your code is not complete but a guess is that your other TokenFilter-implementing classes:
all extend from the ExcerptFilter class, and if you don't want the ExcerptFilter constructor called, then you can't have these classes to extend from it.
Another possible solution:
Upvotes: 1