JAVA设计模式之单一职责原则

时间:2023-03-08 23:08:04
JAVA设计模式之单一职责原则

概念:

就一个类而言应该只有一个因其他变化的原因。

流程:

问题由来:设类或接口类C负责两个不同不同的职责:职责T1,职责T2。当由于职责T1需求改变进而需要修改类C时,可能导致职责T2收到不可预知的影响。

解决方案:分别建立两个类C1、C2,分管职责T1,T2。

优缺点:

1.优点: (1)、降低类的复杂度; (2)、 易维护、易扩展、可读性强 2.缺点: 使类或接口的数目增加, 难以控制。 示例代码 下面代码就没有遵循单一职责模式,如Operation即完成了+又完成了-。

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;
else
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(); Operation myOperation = new Operation("+");
result = myOperation.GetResult(opA, opB);
System.out.println(result); } catch (Exception e) {
e.printStackTrace();
}
}
}

尝试单一职责模式可以拆开

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();
}
}
}