用反射改进工厂模式

原来的工厂模式代码的局限在于每当我们添加一个接口的子类时,工厂类的代码必须改动,我们可以用反射来改进这一点。代码如下:

package com.test;

interface Fruit{
    public void eat();
}

class Apple implements Fruit{
    @Override
    public void eat() {
        System.out.println("eat apple!");        
    }
}

class Orange implements Fruit{
    @Override
    public void eat() {
        System.out.println("eat orange!");        
    }
}

class Factory{
    public static Fruit getInstance(String name){
        Fruit f = null;
        try {
            Class<?> cls = Class.forName(name);
            f = (Fruit)cls.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return f;
    }
}

public class TestDemo {
    public static void main(String[] args) {
        Fruit f = Factory.getInstance("com.test.Apple");
        f.eat();
        f = Factory.getInstance("com.test.Orange");
        f.eat();
    }
}

 

posted @ 2015-12-16 14:20  finalboss1987  阅读(349)  评论(1编辑  收藏  举报