依赖注入的三种方式

本文探讨了三种依赖注入方式:构造方法注入、setter方法注入和接口注入,通过学生和学霸的关系比喻,解释了它们在软件设计中的作用:构造方法注入是长期绑定,setter方法注入是临时合作,接口注入则是按需求助。
摘要由CSDN通过智能技术生成

1、构造方法依赖注入

public class StupidStudent {
    private SmartStudent smartStudent;
    
    public StupidStudent(SmartStudent smartStudent) {
        this.smartStudent = smartStudent;
    }
    
    public doHomewrok() {
        smartStudent.doHomework();
        System.out.println("学渣抄作业");
    }
}

public class StudentTest {
    public static void main(String[] args) {
        SmartStudent smartStudent = new SmartStudent();
        StupidStudent stupidStudent = new StupidStudent(smartStudent);
        stupidStudent.doHomework();
    }
}

这种方式好比学渣从一开始就赖上了一个学霸,并且和这个学霸建立了长期合作关系。

2、setter方法注入

public class StupidStudent {
    private SmartStudent smartStudent;
    
    public void setSmartStudent(SmartStudent smartStudent) {
       this.smartStudent = smartStudent;
    }
    
    public doHomewrok() {
        smartStudent.doHomework();
        System.out.println("学渣抄作业");
    }
}

public class StudentTest {
    public static void main(String[] args) {
        SmartStudent smartStudent = new SmartStudent();
        StupidStudent stupidStudent = new StupidStudent();
        stupidStudent.setSmartStudent(smartStudent);
        stupidStudent.doHomework();
    }
}

这种方式学霸和学渣只是暂时的合作关系,如果学渣赖上了另一个学霸(调用set()方法传入了另一个对象),那么学渣和学霸的合作关系就结束了。

3、接口注入

public class StupidStudent {
    public void doHomewrok(SmartStudent smartStudent) {
        smartStudent.doHomework();
        System.out.println("学渣抄作业");
    }
}
public class StudentTest {
    public static void main(String[] args) {
        SmartStudent smartStudent = new SmartStudent();
        StupidStudent stupidStudent = new StupidStudent();
        stupidStudent.doHomework(smartStudent);
    }
}

采用这种注入方式,学渣只是在做作业时,才临时抱佛脚地找一下学霸。 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值