首页 > 解决方案 > 工厂创建的产品中的静态方法

问题描述

我有一家生产不同类型产品的工厂:

public class Factory {
    public Product createProduct(String type) {
        if(type.equals("Product1")) {
            return new Product1();
        }
        else if(type.equals("Product2")) {
            return new Product2();
        }
    }
}

产品类别如下所示:

public abstract class Product {
    public static doSomething() {
        //...
    }
}

public class Product1 extends Product {
    //...
}

public class Product2 extends Product {
    //...
}

根据我想调用doSomething()相应类的字符串值。如何doSomething()在不创建实例的情况下调用相应的类?有没有比创建 if-else 语句更好的方法,如下所示?

if(type.equals("Product1")) {
    //call doSomething() on Product1 class
}
else if(type.equals("Product2")) {
    //call doSomething() on Product2 class
}

标签: javastaticfactory

解决方案


我的想法是使用反射:

Factory factory = new Factory();

Product product = factory.createProduct("Product1");

try{
    
    //get the method `doSomething` from product reference.
    Method doSomethingMethod = product.getClass().getMethod("doSomething");

    //invoke the method from product reference
    doSomethingMethod.invoke(product);

catch(Exception e){ 
    e.printStackTrace(); 
}

但我的问题是你为什么不直接打电话Product.doSomething()

因为这个方法static意味着你不能在子类中覆盖它。


推荐阅读