对象工厂
public class ObjectFactory<T> {
private Class<T> type; //定义私有数据成员,保存要创建的对象信息
public ObjectFactory(Class<T> type) {//构造函数传入要创建的对象类型信息
this.type = type;
}
public T create() {//对象工厂的creat方法负责生产一个T类型的对象,利用newInstance
T o = null;
try {
o= type.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return o;
}
}
Car对象
public class Car {
public String s = null;
public Car(){
s = "Car";
}
@Override
public String toString(){
return s;
}
}
测试
public class Test {
public static void main(String[] args) {
//首先创建一个负责生产Car的对象工厂,传进去需要创建类的Class信息
ObjectFactory<Car>carFactory = new ObjectFactory<>(Car.class);
Car objCar = carFactory.create();//由对象工厂负责产生car对象
System.out.println(carFactory.create().toString());
}
}
输出