为什么我应该使用createComponent而不是自己创建实例?
这更多是一个概念性问题.
This is more of a conceptual question.
我必须处理必须创建动态h:dataTable
的功能.每当我创建一个组件时,我都会做类似的事情:
I had to work on a functionality that had to create a dynamic h:dataTable
. And whenever I created a component, I did something similar to this:
DataTable table = (DataTable) FacesContext.getCurrentInstance().getApplication()
.createComponent(DataTable.COMPONENT_TYPE);
使用FacesContext
为我创建所有内容.
Using the FacesContext
to create everything for me.
但是我可以简单地做到这一点:
However I could just as simply have done this:
DataTable table = new DataTable();
我之所以采用第一种方式,是因为我在开发时阅读的所有教程和材料都采用了这种方式,但是我却没有清楚的答案.
The reason I did it in the first way is that all the tutorials and material I read while developing did it that way, but I never got a clear answer why.
有没有一个真正的原因,为什么第一个要比第二个好?
Is there an actual reason why the first is better than the second?
Application#createComponent()
添加了一个额外的抽象层,允许运行时多态性和可插入性.具体实现可以通过faces-config.xml
中的<component>
条目进行配置,而该条目又可以通过JAR提供.这允许更改实现而无需重写/重新编译代码.
The Application#createComponent()
adds an extra abstract layer allowing runtime polymorphism and pluggability. The concrete implementation is configurable by <component>
entry in faces-config.xml
which could in turn be provided via a JAR. This allows changing implementation without rewriting/recompiling the code.
就像JDBC API的工作方式一样:您不执行new SomeDriver()
,但是您执行Class.forName(someDriverClassName)
,这允许驱动程序不成为编译时依赖性,因此JDBC代码可在许多DB供应商之间移植而无需重写/重新编译.
It's exactly like as how JDBC API works: you don't do new SomeDriver()
, but you do Class.forName(someDriverClassName)
which allows the driver to not be a compiletime dependency and thus your JDBC code to be portable across many DB vendors without rewriting/recompiling.
但是,如果应用程序仅用于内部使用"并且不打算分发(因此所有代码始终在您的控制之下),那么运行时多态性就没有太大的优势,而且可能会增加(非常小) )的开销.
However, if the application is for "internal usage" only and not intented to be distributable (and thus all the code is always full under you control), then runtime polymorphism has not a so big advantage and may add (very minor) overhead.