下午的工厂模式需要解决一个问题,需要根据传入的类型返回相应的数据类型的对象,因为之前的方案需要返回Object这个万能对象,但是弊端就是在使用工厂模式的时候,进行向下转型,为了规避这个问题,可以使用泛型,来解决动态返回类型的问题,代码如下:

public static <T> T getService(Class<T> clazz,String serviceName){
try {
return (T)ServiceFactory.class.forName(properties.getProperty(serviceName)).newInstance();
} catch (Exception e) {
//deal exception
System.out.println("Factory error!!!\n"+e.getMessage());
}
return null;
}


相关文章:

  • 2022-12-23
  • 2021-07-14
  • 2022-01-16
  • 2022-03-02
  • 2022-01-10
  • 2022-12-23
猜你喜欢
  • 2021-08-03
  • 2021-12-15
  • 2021-10-26
  • 2022-01-13
  • 2021-11-24
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案