Zero coupling? Abstract coupling? Specific coupling?

Zero coupling refers to two or more 组件之间没有任何依赖关系, independent of each other 不会因为一个组件的变化而影响其他组件. Zero coupling is an ideal state, but it is difficult to achieve in actual development because different modules usually need to interact and cooperate in some way.

Abstract coupling means 组件之间的依赖关系是通过抽象的接口或协议来实现的that components only focus on the dependence on the interface, without caring about the specific implementation. Abstract coupling can achieve loose coupling, making components more flexible, scalable, and easier to maintain.

package com.wjr;

interface MessageSender{
    
    
    void sendMessage(String message);
}
class EmailSender implements MessageSender{
    
    
    @Override
    public void sendMessage(String message) {
    
    
         System.out.println("发送邮件----"+message);
    }
}
 class MessageService{
    
    
    private MessageSender messageSender ;
    public MessageService(MessageSender messageSender){
    
    
        this.messageSender=messageSender;
    }
    public void sendMessage(String message){
    
    
        messageSender.sendMessage(message);
    }
}
public class abstractCoupling{
    
    
    public static void main(String[] args) {
    
    
        MessageSender sender=new EmailSender();
        MessageService service=new MessageService(sender);
        service.sendMessage("hello,抽象耦合");
    }
}

Output:

发送邮件----hello,抽象耦合

Specific coupling refers to组件之间的依赖关系是通过具体的类、对象或接口来实现的

package com.wjr;

class MessageService {
    
    
    public void sendMessage(String message) {
    
    
       System.out.println("发送邮件---"+message);
    }
}

 class Main {
    
    
    public static void main(String[] args) {
    
    
        MessageService service = new MessageService();
        service.sendMessage("Hello, 具体耦合!");
    }
}

The output looks like this:

发送邮件---Hello, 具体耦合!

Guess you like

Origin blog.csdn.net/m0_64365419/article/details/133127318
Recommended