Spring IoC 的实现机制

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. }

猜你喜欢

转载自www.cnblogs.com/chinaifae/p/10443123.html
今日推荐