简单工厂模式

浪子不回头ぞ 提交于 2020-01-18 02:56:43

作用

  • 为类的创建提供统一的接口
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类");
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!