记录一下学习工厂方法的心得
工厂方法能更方便的为我们实例化对象。
先定义接口
package com.sunny.project.factory;
public interface Student {
public void introduceSelf();
}
简单弄两个实现类
package com.sunny.project.factory;
public class S1 implements Student {
@Override
public void introduceSelf() {
System.out.println("大家好,我叫小虎!");
}
}
package com.sunny.project.factory;
public class S2 implements Student {
@Override
public void introduceSelf() {
System.out.println("大家好,我叫小文丽!");
}
}
接下来写我们的工厂类:这里我们用到反射机制通过类名来是实例化对象
package com.sunny.project.factory;
public class StudentFactory {
public Student getStudentByClass(String className) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
Student student=(Student) Class.forName(className).newInstance();
return student;
}
}
测试一下 需要注意这里的类名要写全名,只写单个类名会报错找不到该类。
package com.sunny.project.factory;
public class factoryTest {
public static void main(String[] args){
try {
Student student=new StudentFactory().getStudentByClass("com.sunny.project.factory.S2");
student.introduceSelf();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
}
结果没问题,我们只需要类名便可实例化出对象。最后不得不感慨反射真的很强大!