2017-02-13 27 views
0

我有一个类hirachy,如:Java的构造,使已经是正确的子类

class Main{ 
    Main(Object input){ /* */} 
} 

class SubA extends Main{ 
    SubA(Object input){ 
    super(input); 
    // ... 
    } 
} 

class SubB extends Main{ 
    SubB(Object input){ 
     super(input); 
     // ... 
    } 

} 

什么我试图impement是,的Main构造已经构造取决于在inputparameters一个子类。像这样:

// Non working example 
class Main{ 
    Main(Object input){ 

    if (input.fullfillsSomeCond()) { return new SubA(input); } 
    if (input.fullfillsSomeOtherCond()) { return new SubB(input); } 

    } 
} 

这是非常不起作用的,因为我会因为递归而产生无限循环。有更好的建筑巫婆允许 Main somthing = new Main(myInput);已经构建了正确的子类吗?

+1

我认为,根据超类中指定的条件,不允许超类生成子类类型。也许看工厂模式 - 它是一个众所周知的模式,用于从一组可能性中创建特定的实现(包括子类):[工厂模式](https://en.wikipedia.org/wiki/Factory_method_pattern) –

+2

无法在构造函数中返回任何内容。看看[工厂模式](https://www.tutorialspoint.com/design_pattern/factory_pattern.htm)。含义:不要使用构造函数,而要使用工厂的方法。 – f1sh

+1

至少,你正试图从构造函数返回一个值!这在java中是不可能的 –

回答

3

这是不可能的这种利用构造函数,但你可以使用一个工厂方法做:

class Main{ 
    Main(Object input){} 

    public static Main create(Object input) { 
     if (input.fullfillsSomeCond()) { return new SubA(input); } 
     if (input.fullfillsSomeOtherCond()) { return new SubB(input); } 
     // You might want to handle the case where input does not 
     // meet any of the above criteria. 
     throw new IllegalArgumentException("input must be either A or B!"); 
    } 
} 

用法:

// Instead of new Main(input): 
Main oMain = Main.create(myInput); 

随着你可能想使Main抽象和其CTOR protected

这里的缺点是Main必须“知道”它的子类和条件。但如果可以通过ctor完成的话,情况也是如此。

+1

这可能是最简洁的方法来解决问题 – Gikkman

+0

好的。我将使用这种模式。谢谢。 – BerndGit