A small payroll program which pays employees a salary or an amount based on how many hours they've worked in a month (Hourly paid employees only) Here is one of two class diagrams I have produced:

Class Diagram 1

This version uses two child classes to define two types of employees and inherits the base attributes from the Employee parent class and the two child classes have their own methods to pay the two kinds of employees.

My other version however looks like this:

Class Diagram 2

This version uses method overriding based on what type of employee is being paid.

Which is more suitable in terms of implementation based on the other classes and their relationships? Will implementing one over the other have any kind of drastic effect?

有帮助吗?

解决方案

I wouldn't subclass Employee at all. I'd maybe model it as Employee HAS a PaymentStrategy, which is subclassed with HourlyPaymentStrategy, SalaryPaymentStrategy, etc.

To expand as to why: In statically-typed languages like Java and C#, an object can't change its type once instantiated. So, using inheritance, an hourly employee could never become a salaried employee, whereas, with composition, you could replace his PaymentStrategy property from an instance of HourlyPaymentStrategy with SalaryPaymentStrategy.

其他提示

Yet another possibility is to have only one employee type but a hierarchy of pay types.

abstract class PayType
{
    public abstract decimal CalculateSalary();
}

class HourlyRate : PayType
{
}

class Salary : PayType
{
}

The employees would have a PayType property.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top