Single responsibility principle
Single responsibility principle: A class should have only one reason to change, that is, a class should only be responsible for one business logic.
Origin of the problem: Class T is responsible for t1 and T2. When class T is modified by T1J, problems may occur in class T and responsibility T2 may be affected. Solution: Follow the single responsibility principle and rewrite class T to ensure that each class is responsible for one responsibility. The demo:
There is an Animal class with breath function. The general idea is as follows:
class Animal {
public void breathe(String animal) {
System.out.println(animal + "Breathe the air"); }}Copy the code
When you create an Animal instance, you can call breathe.
public class SingletonResponsibility {
public static void main(String[] args) {
Animal animal = new Animal();
animal.breathe("Birds");
animal.breathe("The lion"); // Logical error: fish should breathe water animal.breathe("Fish"); }}Copy the code
We find that when the breathe method is called, the output does not change if fish are passed in. However, this is logically wrong. # # # # # # # # # # # # # # # # # #
Improvement idea 1: Judge in the breathe method
Through judgment, different treatment: if fish, output “breathing water”; Other animals, output “breathing air”; The benefits of doing this are: being able to expose correct business logic; But it violates the single-responsibility principle: the class Animal needs to make type judgments in addition to the normal business of Roger.
Class Animal1 {public void breathe(String animal) {public void breathe(String animal) { There is no new single responsibility principle, this approach requires that in addition to performing normal business logic, // it also needs to judge Animal.if ("Fish".equals(animal)) {
System.out.println(animal + "Breathing water");
} else {
System.out.println(animal + "Breathe the air"); }}}Copy the code
Improvement idea 2: Split classes and methods
To ensure that we follow the single responsibility principle, we can split classes and methods and make sure that they are logically correct.
Class Animal2 {// Improved: added a method to breathe water, which violates the single responsibility principle at the class level, but follows the method. // Note: In practice, the single responsibility principle refers to following a single business logic. public void breathe(String animal) { System.out.println(animal +"Breathe the air");
}
public void breatheWater(String animal) {
System.out.println(animal + "Breathing water"); }}Copy the code
Advantages of a single responsibility:
1. Reduce the class responsibility, so that a class is only responsible for one business logic; 2. Improve readability and maintainability of the project; 3. J Reduce the risk of project change;
Matters needing attention:
In projects, we should try to follow the single responsibility principle, but violate it when the business logic is simple.