IOC控制反转理解
Java资料站
共 6167字,需浏览 13分钟
·
2021-05-14 12:28
点击上方蓝色字体,选择“标星公众号”
优质文章,第一时间送达
1. IOC基础
2. IOC推导与理解
2.1、最基本的实现方式
interface Meizi {
public void describe();
}
class Yujie implements Meizi{
@Override
public void describe() {
System.out.println("御姐~");
}
}
//这里只列出一种女生类型的具体实现,其他的类似
interface Nan {
public void getMeizi();
}
class yihao implements Nan{
@Override
public void getMeizi() {
Meizi meizi = new Yujie();
meizi.describe();
}
}
class erhao implements Nan{
@Override
public void getMeizi() {
Meizi meizi = new Yujie();
meizi.describe();
}
}
2.2、采用组合的方式实现
interface Meizi {
public void describe();
}
class Yujie implements Meizi{
@Override
public void describe() {
System.out.println("御姐~");
}
}
//这里只列出一种女生类型的具体实现,其他的类似
interface Nan {
public void getMeizi();
}
class yihao implements Nan{
private Meizi meizi = new Yujie();
@Override
public void getMeizi() {
meizi.describe();
}
}
class erhao implements Nan{
private Meizi meizi = new Yujie();
@Override
public void getMeizi() {
meizi.describe();
}
}
public class Main {
public static void main(String[] args) {
yihao man1 = new yihao();
man1.getMeizi();
erhao man2 = new erhao();
man2.getMeizi();
}
}
2.3、采用聚合方式(松耦合)
interface Meizi {
public void describe();
}
class Yujie implements Meizi{
@Override
public void describe() {
System.out.println("御姐~");
}
}
//这里只列出一种女生类型的具体实现,其他的类似
interface Nan {
public void getMeizi();
}
class yihao implements Nan{
private Meizi meizi;
public void setMeizi(Meizi meizi) {
this.meizi = meizi;
}
@Override
public void getMeizi() {
meizi.describe();
}
}
class erhao implements Nan{
private Meizi meizi;
public void setMeizi(Meizi meizi) {
this.meizi = meizi;
}
@Override
public void getMeizi() {
meizi.describe();
}
}
public class Main {
public static void main(String[] args) {
yihao man1 = new yihao();
man1.setMeizi(new Yujie());
man1.getMeizi();
erhao man2 = new erhao();
man2.setMeizi(new Luoli());
man2.getMeizi();
}
}
3. IOC总结
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:
https://blog.csdn.net/weixin_43808717/article/details/116425554
锋哥最新SpringCloud分布式电商秒杀课程发布
👇👇👇
👆长按上方微信二维码 2 秒
感谢点赞支持下哈
评论