Recently, we have seen the shadows of design patterns in many occasions. We have been investing in algorithms and data structures for a long time. It is very important to find the design patterns. Sometimes code maintenance, reuse, and scalability are better than pure algorithms. So I picked up Daniel's book "big talk Design Patterns" and referred to the blogs of various big cows on the Internet to start my design patterns journey.
Today, we will introduce a single responsibility model.
Concept:
For a class, there should be only one reason for other changes.
Process:
Problem cause: Setup class or Interface Class C has two different responsibilities: Responsibility T1 and responsibility T2. When Class C needs to be modified due to a change in duties T1, it may cause unpredictable impact on duties T2.
Solution: build two classes C1 and C2 respectively, in charge of duties T1 and T2.
Advantages and disadvantages:
1. Advantages: (1) reduce the complexity of the class; (2) ease of maintenance, scalability, and readability; 2. Disadvantages: Increase the number of classes or interfaces, making it difficult to control.
Sample Code The following code does not follow a single responsibility mode. For example, Operation completes + and completes again -.
package Pattern;import java.util.Scanner;class Operation {String operationName;public Operation(String tempOperationName) {operationName = tempOperationName;}public int GetResult(int opA, int opB) {if (operationName.equals("+"))return opA + opB;elsereturn opA - opB;}}public class Pattern {public static void main(String[] args) {try {Scanner input = new Scanner(System.in);int opA, opB, result;opA = input.nextInt();opB = input.nextInt();Operation myOperation = new Operation("+");result = myOperation.GetResult(opA, opB);System.out.println(result);} catch (Exception e) {e.printStackTrace();}}}
A single responsibility model can be separated.
package Pattern;import java.util.Scanner;class AddOperation {public int GetResult(int opA, int opB) {return opA + opB;}}class SubOperation {public int GetResult(int opA, int opB) {return opA - opB;}}public class Pattern {public static void main(String[] args) {try {Scanner input = new Scanner(System.in);int opA, opB, result;opA = input.nextInt();opB = input.nextInt();AddOperation myAddOperation = new AddOperation();result = myAddOperation.GetResult(opA, opB);System.out.println(result);opA = input.nextInt();opB = input.nextInt();SubOperation mySubOperation = new SubOperation();result = mySubOperation.GetResult(opA, opB);System.out.println(result);} catch (Exception e) {e.printStackTrace();}}}