Java的解决方法是传递一个工厂对象,并使用它来创建新的实例。
1.最便捷的工厂对象就是Class对象
用Class对象的话,就可以利用newInstance()创建这个类型的新对象。
class ClassFactory<T>{
T x;
public ClassFactory(Class<T> kind) {
// TODO Auto-generated constructor stub
try {
x = kind.newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Employee{}
public class Xian{
public static void main(String[] args) {
ClassFactory<Employee> fe = new ClassFactory<Employee>(Employee.class);
System.out.println("succeed");
}
}
这种方式并不推荐,只是可以实现。因为newInstance()的使用条件是必须要有默认的构造函数,当函数加上下面一行之后,就会在运行的时候报错(这种错误在编译的时候不会被捕捉到的)。
class ClassFactory<T>{
T x;
public ClassFactory(Class<T> kind) {
// TODO Auto-generated constructor stub
try {
x = kind.newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Employee{}
public class Xian{
public static void main(String[] args) {
ClassFactory<Employee> fe = new ClassFactory<Employee>(Employee.class);
System.out.println("succeed");
ClassFactory<Integer> fe2 = new ClassFactory<Integer>(Integer.class);
}
}
2.建议使用的是显式的工厂
interface FactoryI<T>{
T create();
}
class Foo2<T> {
private T x;
public <F extends FactoryI<T>>Foo2(F factory) {
x = factory.create();
}
}
class IntergeFactory implements FactoryI<Integer>{
@Override
public Integer create() {
return new Integer(0);
}
}
class Widght{
public static class Factory implements FactoryI<Widght> {
public Widght create() {
return new Widght();
}
}
}
public class Factory {
public static void main(String[] args) {
new Foo2<Integer>(new IntergeFactory());
new Foo2<Widght>(new Widght.Factory());
}
}
显式的实现方式也是有两种,第一种是类直接继承接口,第二种是在用静态内部类继承接口。
3.除此之外,还可以利用模板方法设计模式
abstract class GenericCrearte<T>{
final T element;
public GenericCrearte() {
element = create();
}
abstract T create();
}
class App{}
class Creator extends GenericCrearte<App>{
App create(){
return new App();
}
void f(){
System.out.println(element.getClass().getSimpleName());
}
}
public class Factory {
public static void main(String[] args) {
Creator c = new Creator();
c.f();
}
}
其中get() 是模板方法,而Create() 实在子类中定义的,用来产生子类类型的对象。