Basic introduction
In the case of classes, a class should be responsible for only one responsibility. For example, class A is responsible for two different responsibilities: When the requirements of responsibility 1 change and A changes, the execution of responsibility 2 May be wrong, so the granularity of class A needs to be divided into A1 and A2.
Examples of application
- Plan 1
package com.braveway.principle.singleresponsibility; public class SingleResponsibility1 { public static void main(String[] args) { Vehicle vehicle = new Vehicle(); Vehicle.run (" motorcycle "); Vehicle. The run (" car "); Vehicle. The run (" aircraft "); }} // Traffic class // returns to the single responsibility principle // Not all vehicles run on highways. Class Vehicle{public void run(String Vehicle) {system.out.println (Vehicle + "... ); }}Copy the code
- Scheme 2
package com.braveway.principle.singleresponsibility; Public class SingleResponsibility2 {public static void main(String[] args) {}} Follow the single responsibility principle // 2. However, this is done with a big change, which is to separate the class and modify the client // 3. Class RoadVehicle{public void run(String Vehicle) {system.out.println (Vehicle +" road "); }} Class AirVehicle{public void run(String vehicle) {system.out.println (vehicle+" AirVehicle "); }} Class vehicle {public void run(String vehicle) {system.out.println (vehicle+" water "); }}Copy the code
- Plan 3
package com.braveway.principle.singleresponsibility; public class SingleResponsibility3 { public static void main(String[] args) { } } //1. This modification method does not make a major change to the original class, just add method //2. While the single responsibility principle is not observed at the class level, at the method level, Vehicle2{public void run(String vehicle) {system.out.println (vehicle+" on the road..." ); } public void runAir(String vehicle) {system.out.println (vehicle+"... ); } public void runWater(String vehicle) {system.out.println (vehicle+" run on water... ); }}Copy the code
Notes and details
- Reduce the complexity of classes so that each class has only one responsibility
- Improve readability and maintainability of classes
- Reduce the risk of change
- In general, we should adhere to the single responsibility principle, and only if the logic is simple can we violate the single responsibility principle at the code level; Only the number of methods in a class is small enough to maintain the single responsibility principle at the method level