反射与工厂设计模式

/*
工厂设计模式的一般格式:接口+实现对应接口的子类+工厂类
    通过反射技术改进的工厂,不再使用new关键字来实例化对象了
*/
package com.reflect.factory.model;

interface IFruit {
    public abstract void eat();
}
class Apple implements IFruit{
    @Override
    public void eat() {
       System.out.println("【Apple】吃苹果");
    }
}

class Factory {
    private Factory(){}
    public static  IFruit getInstance(String className){        
        IFruit fruit = null; 
        try {
                         //获取到Class类对象
            Class<?> clazz = Class.forName(className);
                        //通过Class对象实例化对象,但不再用new关键字
            fruit=(IFruit)clazz.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        } 
        return fruit;
    }    
}
public class TestDemo {
    public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException {
          IFruit fruit = Factory.getInstance("com.reflect.factory.model.Apple");
          fruit.eat();
    }
}
/*
   上面这个工厂类存在一个缺陷,目前只能产生IFruit的实例化对象,
   如果需要生成其它类的实例化对象,就需要重新创建一个工厂

   如何解决这个问题呢?
      我们可以使用泛型来解决这个缺陷:
      改进版工厂类如下:
*/
class Factory {
    private Factory(){}
    public static <T> T getInstance(String className){
        T obj = null; 
        try {
            Class<?> clazz = Class.forName(className);
            obj=(T)clazz.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        } 
        return obj;
    }    
}

 

posted @ 2017-09-03 21:50  scwyfy  阅读(311)  评论(0编辑  收藏  举报