简单factory 小例子
程序员文章站
2022-03-02 12:41:25
...
接口的定义:
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" 则输出:老虎吃肉
转载于:https://blog.51cto.com/7618153/1265608
上一篇: js 三种弹出框 alert confirm prompt
下一篇: 简单的小例子