接口的定义:

package day14.factory;
public interface Animal {
    public void eat();
}

接口的实现:


package day14.factory;
public class Cat implements Animal {
    @Override
    public void eat() {
        System.out.println("小猫吃鱼");
    }
}
package day14.factory;
public class Dog implements Animal {
    @Override
    public void eat() {
        System.out.println("小狗吃骨头");
    }
}
package day14.factory;
public class Tiger implements Animal {
    @Override
    public void eat() {
        System.out.println("老虎吃肉");
    }
}


工厂:AnimalFactory

package day14.factory;
public class AnimalFactory {
    public static Animal newInstance(String name) throws Exception{
        /*if("老虎".equals(name)){
            return new Tiger();
        }else if("小猫".equals(name)){
            return new Cat();
        }else if("小狗".equals(name)){
            return new Dog();
        }
        return null;*/
        Class c = Class.forName(name);
        Animal a = (Animal) c.newInstance();
        return a;
    }
}


工厂测试:Test

package day14.factory;
public class Test {
    public static void main(String[] args) {
        Animal a;
        try {
            a = AnimalFactory.newInstance("day14.factory.Tiger");
            a.eat();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

结果:输入:"day14.factory.Tiger" 则输出:老虎吃肉