How to decouple the factory pattern decoupling

Decoupling and its necessity

Decoupling, as the name implies, is to decouple and eliminate dependencies. But in program development, if two modules work together, there must be coupling. If there is no dependency between two modules, it means that they are independent, and there will be no possibility of crossover or cooperative work. Therefore, the decoupling we are talking about here is not to eliminate the coupling between codes, but to reduce their dependencies and make the dependencies in a reasonable range.

Low-coupling programming is one of the most basic requirements in our development. It will increase the functional independence of our development and greatly increase the reusability of modules. At the same time, in the later maintenance of the project, the maintenance cost is reduced, and the risk of reconstruction is reduced when the project is upgraded. It is a design philosophy that a qualified programmer must possess.

Analysis of decoupling ideas

At that time, when we explained jdbc, we registered the driver through reflection. We didn't use the DriverManager.registerDriver()method to register the driver anymore, because at that time we introduced a better Class.forName()way to realize the function of registering the driver through reflection. What is the essential difference between these two methods?

DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Class.forName("com.mysql.jdbc.Driver");//此处只是一个字符串
  • The first method will cause the driver to register twice, but this problem will not affect us too much. At most, the execution efficiency will slightly decrease. The more important problem is that when we need to change the database brand, for example, when changing from a MySQL database to an Oracle database, the DriverManager.registerDriver() 会因为依赖具体驱动实现,而导致我们修改源码。而Class.forName() method will not.

  • In other words, when we use some objects that are not frequently created, it is obviously more reasonable to create objects by reflection. When reflection is created, the fully qualified class name of the created class needs to be provided. If this name is written in the java code, the result is that the modification still cannot avoid modifying the source code. Therefore, we need to use a configuration file to configure the fully qualified class name of the class to be created with the configuration file.

  • Summary of decoupling ideas:

    • First: Use reflection to create objects
    • Second: The fully qualified class name used to create the object is configured with the configuration file

Guess you like

Origin blog.csdn.net/weixin_47785112/article/details/107384162