Java简单工厂

利用反射来优化传统的工厂设计

package cn.java.vo;
/**
 * 简单工厂模式:
 * 每当新增接口子类,无需去修改工厂类代码就可以很方便进行接口子类扩容
 * @author LY
 *
 */
interface IFruit {
    void eat();
}
class Apple implements IFruit {
    @Override
    public void eat() {
        System.out.println("[Apple] 吃苹果");
    }
}
class Pear implements IFruit {
    @Override
    public void eat() {
        System.out.println("[Pear] 吃梨子");
    }
}
// 工厂类:
class FruitFactory {
    // 重点:工厂设计模式-构造方法私有化,即工厂类不可以实例化
    private FruitFactory() {}
    public static IFruit getInstance(String className) {
        IFruit fruit = null;
        try {
            // 利用Class类取得类名。然后进行实例化对象
            fruit = (IFruit) Class.forName(className).newInstance();
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return fruit;
    }
}
public class TestFactory {
    public static void main(String[] args) {
        // 此时getInstance()中参数为类名:具体包的下类名,包含路径
        IFruit fruit = FruitFactory.getInstance("cn.java.vo.Apple");
        fruit.eat();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_39026129/article/details/81282381