简单工厂模式UML类图详解:以公司员工管理系统为例
简单工厂模式UML类图详解:以公司员工管理系统为例
本文将以一个公司员工管理系统为例,讲解如何使用简单工厂模式设计程序,并提供相应的UML类图和代码解释。
问题背景
假设一家公司目前有三种职务:经理 (Manager)、销售人员 (Sales) 和程序员 (Programmer)。公司未来预期会扩大规模,因此职务种类也必然会增加。每位员工 (Employee) 的薪资构成包含工资 (Salary) 和奖金 (Bonus)。
简单工厂模式解决方案
我们可以使用简单工厂模式来设计这个系统。该模式的核心思想是定义一个工厂类,负责根据不同的输入参数创建相应的对象。
以下是该系统UML类图的文本描述:
+---------------------+| EmployeeFactory |+---------------------+| + createEmployee() |+---------------------+
^ | |+---------------------+| Employee |+---------------------+| - name: string || - position: string || - salary: float |+---------------------+| + getName() || + getPosition() || + getSalary() |+---------------------+
^ | |+---------------------+| Manager |+---------------------+| - bonus: float |+---------------------+| + getBonus() |+---------------------+
^ | |+---------------------+| Sales |+---------------------+| - bonus: float |+---------------------+| + getBonus() |+---------------------+
^ | |+---------------------+| Programmer |+---------------------+| - bonus: float |+---------------------+| + getBonus() |+---------------------+
类图解释:
- Employee: 员工基类,包含姓名 (name)、职位 (position) 和工资 (salary) 等属性,以及获取这些属性值的方法。* Manager、Sales、Programmer: 具体员工类,继承自Employee,并根据实际情况添加额外的属性和方法,例如奖金 (bonus) 和获取奖金的方法 (getBonus)。* EmployeeFactory: 员工工厂类,包含一个
createEmployee()方法,根据传入的职位信息创建并返回对应类型的员工对象。
**代码示例 (Java):**java// 员工基类abstract class Employee { protected String name; protected String position; protected float salary;
public Employee(String name, String position, float salary) { this.name = name; this.position = position; this.salary = salary; }
// ... getter methods ...}
// 经理类class Manager extends Employee { private float bonus;
public Manager(String name, float salary, float bonus) { super(name, 'Manager', salary); this.bonus = bonus; }
// ... getter method for bonus ...}
// 其他具体员工类...
// 员工工厂类class EmployeeFactory { public static Employee createEmployee(String position, String name, float salary, float bonus) { switch (position) { case 'Manager': return new Manager(name, salary, bonus); case 'Sales': return new Sales(name, salary, bonus); case 'Programmer': return new Programmer(name, salary, bonus); default: throw new IllegalArgumentException('Invalid position.'); } }}
**使用示例:**javaEmployee manager = EmployeeFactory.createEmployee('Manager', 'John Doe', 5000, 1000);Employee sales = EmployeeFactory.createEmployee('Sales', 'Jane Doe', 4000, 500);
总结
通过使用简单工厂模式,我们可以将对象的创建过程封装起来,降低代码耦合度,提高代码可读性和可维护性。当需要添加新的员工类型时,只需修改工厂类即可,无需修改使用工厂类的代码,符合开闭原则。
原文地址: https://www.cveoy.top/t/topic/ELX 著作权归作者所有。请勿转载和采集!