首頁 >Java >java教程 >單一責任原則

單一責任原則

WBOY
WBOY原創
2024-08-25 20:32:03539瀏覽

Single Responsibility Principle

每個軟體元件都應該只有一個且一個職責

軟體元件可以是類別、方法或模組

例如,瑞士軍刀是一種多用途工具,違反了軟體開發的單一責任原則,相反,刀是遵循單一責任的一個很好的例子(因為與瑞士軍刀不同,它只能用於切割可用於切割、打開罐頭、作為萬能鑰匙、剪刀等)

由於無論是現實世界或軟體開發,變化都是不變的,單一職責原則的定義也會隨之改變

每個軟體元件都應該有一個且僅有一個更改的理由


下面的 Employee 類別發生變化的原因有以下三個

  1. 員工屬性變化
  2. 資料庫更改
  3. 稅計算方式的變化
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

/**
 * Employee class has details of employee
 * This class is responsible for saving employee details, getting tax of
 * employee and getting
 * details of employee like name, id, address, contact, etc.
 */
public class Employee {
    private String employeeId;
    private String employeeName;
    private String employeeAddress;
    private String contactNumber;
    private String employeeType;

    public void save() {
        String insert = MyUtil.serializeIntoString(this);
        Connection connection = null;
        Statement statement = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc://mysql://localhost:8080/MyDb", "root", "password");
            statement = connection.createStatement();
            statement.execute("insert into employee values (" + insert + ")");

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void calculateTax() {
        if (this.getEmployeeType().equals("fulltime")) {
            // tax calculation for full time employee
        } else if (this.getEmployeeType().equals("contract")) {
            // tax calculation for contract type employee
        }
    }

    public String getEmployeeId() {
        return employeeId;
    }

    public void setEmployeeId(String employeeId) {
        this.employeeId = employeeId;
    }

    public String getEmployeeName() {
        return employeeName;
    }

    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }

    public String getEmployeeAddress() {
        return employeeAddress;
    }

    public void setEmployeeAddress(String employeeAddress) {
        this.employeeAddress = employeeAddress;
    }

    public String getContactNumber() {
        return contactNumber;
    }

    public void setContactNumber(String contactNumber) {
        this.contactNumber = contactNumber;
    }

    public String getEmployeeType() {
        return employeeType;
    }

    public void setEmployeeType(String employeeType) {
        this.employeeType = employeeType;
    }

}

由於SRP(單一職責原則)建議在類別中只有一個更改原因,因此我們必須在Employee類別中進行一些修改


SRP 變化

現在,Employee 類別中發生變化的原因只有一個

變更原因:員工屬性變更

/**
 * Employee class has details of employee
 */
public class Employee {
    private String employeeId;
    private String employeeName;
    private String employeeAddress;
    private String contactNumber;
    private String employeeType;

    public void save() {
       new EmployeeRepository().save(this);
    }

    public void calculateTax() {
       new TaxCalculator().calculateTax(this);
    }

    public String getEmployeeId() {
        return employeeId;
    }

    public void setEmployeeId(String employeeId) {
        this.employeeId = employeeId;
    }

    public String getEmployeeName() {
        return employeeName;
    }

    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }

    public String getEmployeeAddress() {
        return employeeAddress;
    }

    public void setEmployeeAddress(String employeeAddress) {
        this.employeeAddress = employeeAddress;
    }

    public String getContactNumber() {
        return contactNumber;
    }

    public void setContactNumber(String contactNumber) {
        this.contactNumber = contactNumber;
    }

    public String getEmployeeType() {
        return employeeType;
    }

    public void setEmployeeType(String employeeType) {
        this.employeeType = employeeType;
    }

}

此外,EmployeeRepository 類別中發生變更的原因只有一個

更改原因:資料庫變更

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class EmployeeRepository {

    public void save(Employee employee) {
         String insert = MyUtil.serializeIntoString(employee);
        Connection connection = null;
        Statement statement = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc://mysql://localhost:8080/MyDb", "root", "password");
            statement = connection.createStatement();
            statement.execute("insert into employee values (" + insert + ")");

        } catch (Exception e) {
            e.printStackTrace();
        }
}

}

最後,TaxCalculator 類別中發生變更的原因只有一個

變更原因:稅務計算變更

public class TaxCalculator {

    public void calculateTax(Employee employee) {
        if (employee.getEmployeeType().equals("fulltime")) {
            // tax calculation for full time employee
        } else if (employee.getEmployeeType().equals("contract")) {
            // tax calculation for contract type employee
        }
    }
}

注意:所有 3 個類別現在都遵循單一職責原則,因此遵循兩個定義

建立類別或任何軟體元件時請記住:以高內聚和鬆散耦合為目標

每個軟體元件應該只有一個和一個職責
每個軟體元件都應該有一個且僅有一個更改的理由

以上是單一責任原則的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn