[Dark Horse Programmer Jinan Center] Single Responsibility Model

[Dark Horse Programmer Jinan Center] Single Responsibility Model
Today , I will talk to you about the single responsibility model. From the name, you should be able to think that the core idea of ​​this design pattern is to reduce coupling and emphasize that a class/whole only does one thing. I won't give you a code example today, because this will be easy to understand. You only need to write a class and emphasize a method, and the method only implements one function!
Single Responsibility Pattern: For a class, there should be only one reason for it to change.
Some students will ask, if a class only has one and only one factor to cause its changes, wouldn't the code of our program be very bloated? This situation depends on the situation. In fact, it is also true in life. If we specialize in one thing, we have to give up some other functions. For example, our mobile phones can take pictures, but they are not as professional as digital cameras. Another example is our transportation. Cars are responsible for the road, ships are responsible for the sea, and planes are responsible for the sky. We have to do one thing and let him specialize in one function.
In some specific cases, we only allow a class to assume a specific responsibility. If a class has too many responsibilities, it is equivalent to coupling these responsibilities together. This is taboo in our programming thinking. Programmers have always We are committed to simplifying our code. What we often say is to make the code high cohesion and low coupling, and reduce the coupling of the code, so that if we modify a functional module in the code, we only need to modify the specific The class of the function is enough, so that it will not affect the code of other functions. If we improve the coupling of functional code, the code we design will be very fragile. When a functional code changes, our code design will be damaged, and the impact will be very large.
In actual development, we will find that there are many functions of the software. We cannot blindly separate code and functions. We must judge whether these functions need to be separated. Our separation principle is that we extract and use factories for classes with the same functions. And the strategy pattern, if the function is different, we can make the responsibility of this class single, that is, separate it.
Another is that if this class has many motivations or factors to change it, we need to consider separating it and making its function single.
Today's single responsibility model is not easy to write code or too easy to write code, we have to think according to our project area, when will it be used, and when there is no need to separate classes. As a programmer, we must add our own thinking, not just as a porter of code.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324770066&siteId=291194637