理解java的控制反转和依赖注入

1550阅读 0评论2014-09-24 zhangzheyuk
分类:Android平台

http://blog.163.com/taodengwen@126/blog/static/87199341201191383429693/



点击(此处)折叠或打开

  1. public interface Person {
  2.     void sayHello();
  3. }


  4. public class Chinese implements Person {
  5.     public void sayHello() {
  6.            System.out.println("您好 !");
  7.     }
  8. }


  9. public class American implements Person {

  10.     public void sayHello() {
  11.                 System.out.println("How do you do .");
  12.            }

  13. }



  14. //传统类里此类new Chinese/American
  15. public class User {
  16.     Person p;
  17.     public Person getP() {
  18.          return p;
  19.     }
  20.      //使用setter注入
  21.     public void setP(Person p) {
  22.        this.p = p;
  23.     }
  24.    

  25.    //调用person子类重写的sayHello方法,这里的p并没有实例化
  26.     public void function(){
  27.        p.sayHello();
  28.     }

  29. }


  30. //外部容器

  31. public class Container{

  32.     public static User getBean(){

  33.         Person p=new Chinese();

  34.         User user = new User();

  35.         //由容器‘注入’实例

  36.         user.setP(p);

  37.         return user;

  38.     }

  39. }


  40. public class Test{

  41.     public static void main(String[] args){

  42.            User user = Container.getBean();

  43.            user.function();

  44.     }

  45. }


依赖注入的三种方式:
http://yejiansuo.iteye.com/blog/789895
上一篇:Android在SD卡里写文件
下一篇:SIP 中的Dialog,call,session 和 transaction