Dylan Roberts
Dylan Roberts

Reputation: 3

How to stop the constructor from being called in this instance

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

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285401

Your code is not complete but a guess is that your other TokenFilter-implementing classes:

  • ExcerptFilterStopOnly
  • ExcerptFilterStartAndStop
  • ExcerptFilterStartOnly

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:

  • Yes, have those classes extend from ExcerptFilter but give ExcerptFilter more than one constructor, and strictly control which constructor is called in the child classes by explicitly calling the correct super constructor.

Upvotes: 1

Related Questions