java - 工厂创建的产品中的静态方法
问题描述
我有一家生产不同类型产品的工厂:
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
}
解决方案
我的想法是使用反射:
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
意味着你不能在子类中覆盖它。
推荐阅读
- android - Android (AOSP) 7:在其他模块之前构建模块/修补模块作为构建过程的一部分/修改系统源
- python - 如何让pygame播放下一个声音并启用停止?
- delphi - 主窗体最小化,而其他窗体最大化
- java - 使用spring和JPA将数据从一个表单添加到两个不同的表
- r - 您如何在 deSolve (R) 中实现系统动力学风格的流水线延迟?
- elasticsearch - Elasticsearch 动态模板映射
- unit-testing - Jetbrains Rider - 导出单元测试结果
- pandas - 如何在熊猫数据框中循环遍历具有不同条件的每一列-共享x轴图
- java - 如何小写所有 HashMap 的值?
- c# - RNGCryptoServiceProvider.GetBytes() 返回全零