简单工厂模式
作用
- 为类的创建提供统一的接口
public class ShapeFactory {
public static Shape getShape(String className) {
ClassLoader classLoader = ShapeFactory.class.getClassLoader();
try {
Class<Shape> aClass = (Class<Shape>) classLoader.loadClass(className);
// 实例 instanceof (类);
//自身类.class.isInstance(自身实例或子类实例) 类和实例比对
boolean flag = Shape.class.isAssignableFrom(aClass); //前面时父类,后面时子类 类和类比对
if (flag) {
Shape shape = aClass.newInstance();
return shape;
}
} catch (ClassNotFoundException e) {
throw new RuntimeException("类名错了");
} catch (InstantiationException e) {
throw new RuntimeException("没有无参构造器");
} catch (IllegalAccessException e) {
throw new RuntimeException("修饰符错误");
}
throw new RuntimeException("不是shape类");
}
}
malu