Spring 中的 IoC 的實現原理就是工廠模式加反射機制。git
interface Fruit {
github
public abstract void eat();
spring
}
ui
class Apple implements Fruit {
spa
public void eat(){
code
System.out.println("Apple");
get
}
it
}
io
class Orange implements Fruit {
class
public void eat(){
System.out.println("Orange");
}
}
class Factory {
public static Fruit getInstance(String ClassName) {
Fruit f=null;
try {
f=(Fruit)Class.forName(ClassName).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return f;
}
}
class Client {
public static void main(String[] a) {
Fruit f=Factory.getInstance("io.github.dunwu.spring.Apple");
if(f!=null){
f.eat();
}
}
}