简体   繁体   English

Java - 创建抽象对象的工厂类?

[英]Java - Factory class that creates an abstract object?

I have the 2 following abstract classes:我有以下 2 个抽象类:

public abstract class AbstractCarChecker implements CarService {

}

and the below which extends AbstractCarChecker下面扩展了 AbstractCarChecker

public abstract class CarChecker<T extends Car> extends AbstractCarChecker {

}

I want to have a factory class that will instantiate a CarChecker object, so that all subclasses (eg FordCheckerFactory ) can extend it to create instances.我想要一个工厂类来实例化 CarChecker 对象,以便所有子类(例如FordCheckerFactory )可以扩展它以创建实例。

public class CarCheckerFactory {

    public CarCheckerFactory() { }

    public static CarChecker newFrom(String carName, String carReg) {

        CarChecker carChecker = new CarChecker(carName, carReg);

        return carChecker;
    }

}

However the issue is that I cannot instantiate CarChecker as its abstract.然而问题是我不能将CarChecker实例CarChecker它的抽象。

What is the best approach to this, use an if statement to decide what concrete implementation to return?什么是最好的方法,使用if statement来决定返回什么具体实现? eg pass "ford" into the newFrom method to know to create a FordChecker object?例如,将“福特”传递给newFrom方法以了解创建 FordChecker 对象?

You can do it as follows:你可以这样做:

public static CarChecker newFrom(String carName, String carReg, String className) {
    Class<?> theClass = Class.forName(className);
    Constructor<?> cons = theClass.getConstructor(String.class,String.class);
    CarChecker carChecker = cons.newInstance(new Object[] {carName, carReg });
    return carChecker;
}

where className pertains the name of the concrete class.其中className属于具体类的名称。

You can't create instances of abstract classes (and as a consequence, 'abstract object' just isn't a thing).您不能创建抽象类的实例(因此,“抽象对象”不是一回事)。

The whole notion of factories is that they represent the notion of creating things.工厂的整个概念是它们代表了创造事物的概念。 Therefore, the newFrom method should NOT be static (because then it might as well have been a constructor and the factory as a concept is useless; factories serve the function of having constructors that can have polymorphic behaviour, just like instance methods can).因此, newFrom方法不应该是静态的(因为那么它也可能是一个构造函数,而工厂作为一个概念是无用的;工厂提供具有多态行为的构造函数的功能,就像实例方法一样)。 Thus:因此:

public interface CarCheckerFactory<T extends Car> {
    CarChecker<T> newFrom(String carName, String carReg);
}

public class FordCheckerFactory implements CarCheckerFactory<Ford> {
    return new FordChecker(carName, carReg);
}

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

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