package com.curtis.test.factory;
interface IFruit {
public void eat();
}
class Orange implements IFruit {
@Override
public void eat() {
System.out.println("吃橙子.");
}
}
class Apple implements IFruit {
@Override
public void eat() {
System.out.println("吃苹果.");
}
}
public class TestFactory {
public static void main(String[] args) {
// IFruit apple=new Apple();
// apple.eat();
// IFruit orange=new Orange();
// orange.eat();
IFruit apple = Factory.getInstance(Apple.class);
IFruit orange = Factory.getInstance(Orange.class);
orange.eat();
apple.eat();
}
}
package com.curtis.test.factory;
public class Factory {
public static <T> T getInstance(Class<T> cls) {
try {
return cls.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
打开App,阅读手记