This is my first article on getting started
Statement of the single responsibility principle (single responsibility for classes)
A class does only one job, and only one reason causes the class to change
Advantages of the single responsibility principle
- The class is readable and maintainable
- Class complexity is low, a class is only responsible for one function, its logic is simple
Example of single responsibility principle (Problem raising and resolution)
Suppose there is a class C, which is responsible for two responsibilities, P1 and P2 respectively. When the requirements of responsibility P1 change, it is necessary to modify class C, which may lead to the error of sending responsibility P2, which originally operated normally
Following the single responsibility principle, create two classes C1 and C2, with C1 doing P1 and C2 doing P2, so that changes to either C1 or C2 will not affect each other
Code sample
Demand V1: salary calculation for employees. At the beginning, we will create an employee class with a method to calculate salary
Class Employee{func calculateSalary(name:String) {print("\(name) salary is 100")}} let Employee = Employee() Employee. CalculateSalary (name: "Xiaoming ") // Xiaoming's salary is 100Copy the code
Demand V2: Because employees have different ranks, their salaries are different, so following the principle of single responsibility, we need to subdivide The Employee class into various ranks. The realization code of each rank class is the same as Employee, but the method calculateSalary is different. In actual development, Employee should be defined as a protocol. Each level implements the protocol so that it can be easily extended
protocol EmployeeProtocol{ func calculateSalary(name:String) } class Manager:EmployeeProtocol{ func CalculateSalary (name:String) {print("\(name) salary is 1000")}} Class Staff:EmployeeProtocol{func CalculateSalary (name:String) {print("\(name) salary is 100")}} let manager = Manager() manager.calculateSalary(name: "Manager ") // Manager's salary is 1000 let staff = staff () staff.calculateSalary(name:" staff ") // Staff's salary is 100Copy the code