双面
发布于 2025-06-16 / 43 阅读
0
0

spring框架(控制反转和依赖注入)

在学习spring框架中的小伙伴一定会听说过loc(控制反转)和di(依赖注入),对于初学者来说可能比较难以理解,这篇文章主要是讲解这两个东西

1、什么是耦合度

耦合度,就是对象和对象不可分开的程度,比如以下代码

// 邮件服务类
class EmailService {
    public void sendEmail(String message, String to){
        System.out.println("Sending email to " + to + " with Message=" + message);
    }
}

// 通知客户端类
class NotificationClient {
    // 直接实例化EmailService,导致高耦合
    private EmailService emailService = new EmailService();

    public void sendNotification(String message, String to){
        emailService.sendEmail(message, to);
    }
}

public class Main {
    public static void main(String[] args) {
        NotificationClient client = new NotificationClient();
        client.sendNotification("Hello, this is a notification", "example@example.com");
    }
}

这样在客户类中需要使用邮件类功能,然后直接创建对象的,耦合度就非常高,因为他们是直接引用的,假设,我们需要给邮件服务类换个名字,我们就需要在通知客户类中修改创建对象的代码,虽然这个例子看不出来,因为他只创建了一个对象,但是我们有一百,一千,甚至一万个邮件对象呢?我们修改代码将会变得非常困难,这种关联性很强的代码就是高耦合
我们看一下下面低耦合的代码

interface MessageService {
    void sendMessage(String message, String to);
}

class EmailService implements MessageService {
    @Override
    public void sendMessage(String message, String to) {
        System.out.println("Sending email to " + to + " with Message=" + message);
    }
}

class NotificationClient {
    private MessageService messageService;

    // 使用构造函数进行依赖注入
    public NotificationClient(MessageService messageService) {
        this.messageService = messageService;
    }

    public void sendNotification(String message, String to){
        messageService.sendMessage(message, to);
    }
}

public class Main {
    public static void main(String[] args) {
        NotificationClient client = new NotificationClient(new EmailService());
        client.sendNotification("Hello, this is a notification", "example@example.com");
    }
}

反转权限就是反转对象创建的权限,在之前的面向对象设计中,创建对象的权限是给程序员了,现在创建对象由代码创建,这样,代码和代码之间的耦合度就非常低了,而依赖注入呢,就是当一个类中需要创建另一个类的对象,这是我们代码高耦合的关键,高耦合的原因是在类中直接写死了对象的创建和调用,所以我们使用依赖注入的方式来在类中建立另一个对象的使用,这样就可以达到解耦的效果


评论