system sys pub nts 实例化 eat public oid
没有利用反射机制定义的简单工厂类
- interface Fruit {
- public void eat();
- }
- class Apple implements Fruit {
- public void eat() {
- System.out.println("吃苹果");
- }
- }
- class Orange implements Fruit {
- public void eat() {
- System.out.println("吃橘子");
- }
- }
- //下面定义一个工厂,取得子类的实例化对象;
- class Factory {
- public static Fruit getInstance(String className) {
- if ("apple".equals(className)) {
- return new Apple();
- } else if ("orange".equals(className)) {
- return new Orange();
- } else {
- return null;
- }
- }
- }
- public class Test {
- public static void main(String args[]) {
- Fruit f = Factory.getInstance("apple");
- f.eat();
- }
- }
java 工厂设计模式初步
来源: http://www.bubuko.com/infodetail-2253123.html