1. 程式人生 > >Spring IoC 的實現機制

Spring IoC 的實現機制

pri ioc 實現原理 void imp ring new sna clas

Spring 中的 IoC 的實現原理就是工廠模式加反射機制。

  1. interface Fruit {

  2. public abstract void eat();

  3. }

  4. class Apple implements Fruit {

  5. public void eat(){

  6. System.out.println("Apple");

  7. }

  8. }

  9. class Orange implements Fruit {

  10. public void eat(){

  11. System.out.println("Orange");

  12. }

  13. }

  14. class Factory {

  15. public static Fruit getInstance(String ClassName) {

  16. Fruit f=null;

  17. try {

  18. f=(Fruit)Class.forName(ClassName).newInstance();

  19. } catch (Exception e) {

  20. e.printStackTrace();

  21. }

  22. return f;

  23. }

  24. }

  25. class Client {

  26. public static void main(String[] a) {

  27. Fruit f=Factory.getInstance("io.github.dunwu.spring.Apple");

  28. if(f!=null){

  29. f.eat();

  30. }

  31. }

  32. }

Spring IoC 的實現機制