單一責任原則(Single Responsibility Principle, SRP)

目錄

design pattern 以java 為例

單一責任原則(Single Responsibility Principle, SRP)

描述

一個class應該只負責一件事

範例

我們現在要做員工的報表,所以可以將員工跟報表拆分成不同class,如果員工內容有變,輸出報表則不用變

Employee

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Employee {
private String id;
private String name;
private String department;

// Constructor, getters, and setters
public Employee(String id, String name, String department) {
this.id = id;
this.name = name;
this.department = department;
}

// Employee related methods
public String getId() { return id; }
public String getName() { return name; }
public String getDepartment() { return department; }
}

EmployeeReportFormatter

1
2
3
4
5
6
7
8
9
10
class EmployeeReportFormatter {
public String formatToCSV(Employee employee) {
return String.format("%s,%s,%s\n", employee.getId(), employee.getName(), employee.getDepartment());
}

public String formatToXML(Employee employee) {
return String.format("<employee><id>%s</id><name>%s</name><department>%s</department></employee>",
employee.getId(), employee.getName(), employee.getDepartment());
}
}

實作

1
2
3
4
5
6
7
8
9
10
11
12
public class SRPDemo {
public static void main(String[] args) {
Employee emp = new Employee("1", "John Doe", "Engineering");
EmployeeReportFormatter formatter = new EmployeeReportFormatter();

System.out.println("CSV Format:");
System.out.println(formatter.formatToCSV(emp));

System.out.println("XML Format:");
System.out.println(formatter.formatToXML(emp));
}
}
  • output
    1
    2
    3
    4
    5
    CSV Format:
    1,John Doe,Engineering

    XML Format:
    <employee><id>1</id><name>John Doe</name><department>Engineering</department></employee>

單一責任原則(Single Responsibility Principle, SRP)
https://shengshengyang.github.io/2024/03/31/srp/
作者
Dean Yang
發布於
2024年3月31日
許可協議