Java的工厂模式(二)

  除了上文提到的方法之外,还可以使用Java的反射机制,这样就能使用类名称来加载所需要的类。我们只需改变工厂类和驱动类就可以了。

  FruitFactory.java

package com.muggle.project;
//水果工厂
public class FruitFactory {

    public FruitInterface getFruit(String key) {
        if("Banana".equals(key)) {
            return new Banana();        }
        else if ("Apple".equals(key)) {
            return new Apple();
        }
        else {
            return null;
        }
    }
    
    
    /*        使用类名称来创建对象
    */
    public FruitInterface getFruitByClass(String calssName) {
        try {
            FruitInterface fruit=(FruitInterface) Class.forName(calssName).newInstance();
            return fruit;
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return null;
    }
}

  使用动态加载的方法,就可以直接用类名称来创建对象了。

  TestDrive.java

package com.muggle.project;

public class TestDrive {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
/*        不用工厂模式的原始方法
*/
//        FruitInterface banana=new Banana();
//        banana.produce();
//        FruitInterface apple=new Apple();
//        apple.produce();

        
/*        用工厂模式的原始方法
*/
//        FruitFactory factory =new FruitFactory();
//        FruitInterface banana=factory.getFruit("Banana");
//        banana.produce();
        
        FruitFactory factory =new FruitFactory();
        FruitInterface banana=factory.getFruitByClass(Banana.class.getName());
        banana.produce();
    }

}

 

posted @ 2018-04-16 13:20  Mugglean  阅读(102)  评论(0编辑  收藏  举报