面向对象设计原则-单一职责示例

2023-05-05 14:10:13 浏览数 (1)

代码语言:javascript复制
// Bad example without SRP
class Employee {
    private String name;
    private int id;
    private int salary;

    public Employee(String name, int id, int salary) {
        this.name = name;
        this.id = id;
        this.salary = salary;
    }

    public void calculateSalary() {
        // Complex calculation based on employee's type, experience, etc.
        // ...
    }

    public void save() {
        // Save employee data to database
        // ...
    }

    public void sendEmail() {
        // Send email to employee
        // ...
    }
}

// Good example with SRP
class Employee {
    private String name;
    private int id;
    private int salary;

    public Employee(String name, int id, int salary) {
        this.name = name;
        this.id = id;
        this.salary = salary;
    }

    public int calculateSalary() {
        // Complex calculation based on employee's type, experience, etc.
        // ...
        return salary;
    }
}

class EmployeeDAO {
    public void save(Employee employee) {
        // Save employee data to database
        // ...
    }
}

class EmailService {
    public void sendEmail(Employee employee) {
        // Send email to employee
        // ...
    }
}

在这个例子中,我们定义了一个Employee类,它负责保存员工的姓名、工号和薪水,并且实现了三个方法:calculateSalary、save和sendEmail。

在不遵循SRP原则的情况下,Employee类承担了太多的职责:它既要计算员工的薪水,还要保存员工的数据,还要发送邮件给员工。这样,Employee类的代码变得非常复杂,难以维护和修改,而且不利于代码的重用和测试。

为了遵循SRP原则,我们可以将Employee类拆分成三个单一职责的类:Employee、EmployeeDAO和EmailService。其中,Employee类只负责保存员工的姓名、工号和薪水,而calculateSalary方法则被移到Employee类中,以计算员工的薪水。EmployeeDAO类负责保存员工的数据到数据库中,而EmailService则负责向员工发送邮件。这样,每个类都只承担了自己的职责,代码变得更加清晰和易于理解,而且有利于代码的重用和测试。

0 人点赞