Android decoupling (1) interface-based module decoupling

1. How to implement interface-based module decoupling

Interface-based module decoupling can be achieved through the following steps:

1. Create a public module (base module), and define all interfaces (interfaces) that need to be called or communicated by other modules. For example:

// base module
public interface IPayService {
    
    
    // 支付验证方法
    boolean verifyPayment(String orderId);
}

public interface ILoginService {
    
    
    // 获取用户信息方法
    User getUserInfo();
}

2. Implement these interfaces in each sub-module, and register your own implementation class (implementation) with the public module. There are two registration methods here: one is to use Java SPI technology to create a text file with the fully qualified name of the interface in the src/main/resources/META-INF/services directory, and write the corresponding implementation class in it Fully qualified name; the other is to use compile-time annotations, add @AutoService(Interface.class) annotations to the implementation class, and introduce the Google AutoService library. For example:

// pay module
@AutoService(IPayService.class)
public class PayServiceImpl implements IPayService {
    
    
    @Override
    public boolean verifyPayment(String orderId) {
    
    
        // 实现支付验证逻辑
        return true;
    }
}

// login module
@AutoService(ILoginService.class)
public class LoginServiceImpl implements ILoginService {
    @Override
    public User getUserInfo() {
        // 实现获取用户信息逻辑
        return new User("Tom", 18);
    }
}

3. Create a component management class (ComponentManager) in the public module, and use Java SPI technology to load the correspondence between all registered component interfaces and component implementation classes, and provide a static method to obtain correspondence according to the component interface type Components implement class objects. For example:

// base module
public class ComponentManager {
    
    

    private static final Map<Class<?>, Object> COMPONENT_MAP = new HashMap<>();

    static {
    
    
        // 使用Java SPI技术加载所有已注册的组件接口和组件实现类之间对应关系
        ServiceLoader.load(Object.class).forEach(service -> {
    
    
            Class<?>[] interfaces = service.getClass().getInterfaces();
            if (interfaces != null && interfaces.length > 0) {
    
    
                for (Class<?> interfaceClass : interfaces) {
    
    
                    COMPONENT_MAP.put(interfaceClass, service);
                }
            }
        });
    }

    // 提供一个静态方法来根据组件接口类型获取对应组件实现类对象
    public static <T> T getComponent(Class<T> interfaceClass) {
    
    
        return (T) COMPONENT_MAP.get(interfaceClass);
    }
}

In other modules, the implementation class object of the corresponding interface is obtained through the component management class (ComponentManager) of the public module, and its method is called for communication or function execution. For example:

// social module
public class SocialActivity extends AppCompatActivity {
    
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_social);

        // 通过公共module的组件管理类(ComponentManager)获取到登录模块的接口实现类对象
        ILoginService loginService = ComponentManager.getComponent(ILoginService.class);

        // 调用登录模块的接口方法获取用户信息
        User user = loginService.getUserInfo();

        // 显示用户信息
        TextView tvUserName = findViewById(R.id.tv_user_name);
        TextView tvUserAge = findViewById(R.id.tv_user_age);
        tvUserName.setText(user.getName());
        tvUserAge.setText(String.valueOf(user.getAge()));
    }
}

2. Advantages and disadvantages of interface-based module decoupling

Interface-based module decoupling has the following advantages:

1. Thorough decoupling, there is no need for any dependencies or references between sub-modules, only the public modules need to be relied upon.
2. The communication is simple and efficient, supports all basic types and class types, and is as convenient as calling the internal interface of the module.
3. The implementation is flexible and diverse. Different interface implementation classes can be selected according to different scenarios or needs, and dynamically replaced or switched.

Interface-based module decoupling also has the following disadvantages:

**1.** It is necessary to create an additional public module and define all interfaces that need to be called or communicated by other modules, which increases the amount of code and maintenance costs.
**2.** It is necessary to use Java SPI technology or compile-time annotations to register the correspondence between component interfaces and component implementation classes, which increases compilation time and runtime overhead.
**3.** You need to pay attention to avoid problems such as circular dependencies or repeated registrations, otherwise it may cause program crashes or exceptions.

3. Usage scenarios of interface-based module decoupling

Interface-based module decoupling is suitable for the following usage scenarios:

1. When the project has many and complex functions, it is necessary to split an app main module into multiple sub-modules, and each sub-module is responsible for an independent function or business scenario.
2. When sub-modules need to call or communicate with each other, a way is needed to achieve decoupling and communication between sub-modules.
When calling or communicating between submodules involves multiple data types, a way is needed to support all basic types and class types.
3. When the call or communication between sub-modules may change, a way is needed to achieve flexible switching or replacement.

at last

If you want to become an architect or want to break through the 20-30K salary range, then don't be limited to coding and business, but you must be able to select models, expand, and improve programming thinking. In addition, a good career plan is also very important, and the habit of learning is very important, but the most important thing is to be able to persevere. Any plan that cannot be implemented consistently is empty talk.

If you have no direction, here I would like to share with you a set of "Advanced Notes on the Eight Major Modules of Android" written by the senior architect of Ali, to help you organize the messy, scattered and fragmented knowledge systematically, so that you can systematically and efficiently Master the various knowledge points of Android development.
img
Compared with the fragmented content we usually read, the knowledge points of this note are more systematic, easier to understand and remember, and are arranged strictly according to the knowledge system.

Welcome everyone to support with one click and three links. If you need the information in the article, you can directly scan the CSDN official certification WeChat card at the end of the article to get it for free↓↓↓

PS: There is also a ChatGPT robot in the group, which can answer your work or technical questions
picture

Guess you like

Origin blog.csdn.net/weixin_43440181/article/details/131962584