简体   繁体   English

如何阻止在这种情况下调用构造函数

[英]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. 调用factory方法时,将调用我的私有构造函数,这会导致该类的结果产生影响。

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. 我将print语句放入构造函数中,以查看是否调用了它,无论工厂提供了什么字符串,都将导致调用。

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. 工厂应在ExcerptFilter中返回嵌套类的正确实例。 It shouldn't make any calls to the constructor UNLESS the who parameters to factory() are zero length or null. 除非factory()的who参数为零长度或null,否则它不应对构造函数进行任何调用。

Your code is not complete but a guess is that your other TokenFilter-implementing classes: 您的代码不完整,但是您可能会猜到其他TokenFilter实现类:

  • ExcerptFilterStopOnly ExcerptFilterStopOnly
  • ExcerptFilterStartAndStop ExcerptFilterStartAndStop
  • ExcerptFilterStartOnly 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. 所有这些都从ExcerptFilter类扩展,并且如果您不希望调用ExcerptFilter构造函数,那么就不能让这些类从其扩展。

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. 是的,让这些类从ExcerptFilter扩展而给ExcerptFilter多个构造函数,并通过显式调用正确的超级构造函数来严格控制在子类中调用哪个构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM