> Java > java지도 시간 > 본문

단일 책임 원칙

WBOY
풀어 주다: 2024-08-25 20:32:03
원래의
411명이 탐색했습니다.

Single Responsibility Principle

모든 소프트웨어 구성 요소에는 단 하나의 책임만 있어야 합니다

소프트웨어 구성요소는 클래스, 메소드 또는 모듈일 수 있습니다

예: 스위스 군용 칼은 소프트웨어 개발의 단일 책임 원칙을 위반하는 다목적 도구입니다. 대신 칼은 단일 책임을 따르는 좋은 예입니다(스위스 군용 칼과 달리 절단에만 사용할 수 있으므로) 자르기, 캔 따기, 마스터키, 가위 등으로 사용할 수 있는 것)

현실 세계에서든 소프트웨어 개발에서든 변화는 끊임없이 일어나기 때문에 단일 책임 원칙의 정의도 그에 따라 변합니다.

모든 소프트웨어 구성 요소에는 변경해야 하는 단 하나의 이유가 있어야 합니다


아래 직원 클래스에서 변경이 발생할 수 있는 이유는 세 가지입니다

  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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!