欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

工厂模式(依赖反射)

程序员文章站 2022-03-09 21:44:50
...

工厂方法:

public class HumanFactory2 {
    public static Human getHuman(String className) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        Class clazz = Class.forName(className);
        return (Human)clazz.newInstance();
    }
}

human和实现类

public interface Human {
    void say();
}
public class WhilteHuman implements Human {
    @Override
    public void say () {
        System.out.println(“我是白种人”);
    }
}
public class YellowFactory implements Human {
    @Override
    public void say() {
        System.out.println(”我是黄种人”);
    }
}

测试类:

public class TestSimpleFactory {
    public static void main(String[] args) throws IllegalAccessException, InstantiationException, ClassNotFoundException {
        Human human = HumanFactory2.getHuman("simpleFactory.human.WhiteHuman");
        human.say();
    }
}