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

反射与工厂设计模式

程序员文章站 2022-03-01 15:11:32
...

一、定义接口

interface  IFuit{
    void eat();
}

二、定义类实现接口 

class Apple implements IFuit{

    @Override
    public void eat() {
        System.out.println ("吃苹果" );
    }
}
class Orange implements IFuit{
    @Override
    public void eat() {
        System.out.println ("吃橘子" );
    }
}
class FruitFactory{
    private FruitFactory(){
    }
    public static IFuit getFuitInstance(String className) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
      Class classz =  Class.forName ( className );

            return (IFuit) classz.newInstance ();
    }
}

三、测试 

public class Test {
public static void main(String[] args) throws IllegalAccessException, InstantiationException, ClassNotFoundException { ;
        IFuit fuit=FruitFactory.getFuitInstance ( "反射.Apple" );
        fuit.eat ();
    }
}

四、运行结果 

反射与工厂设计模式