java员工管理系统工厂模式代码
时间: 2024-05-13 07:12:30 浏览: 109
Java员工管理系统可以使用工厂模式进行设计和实现。工厂模式是一种创建型设计模式,它提供了一种创建对象的最佳方式,通过使用工厂方法来解决对象创建的问题。以下是Java员工管理系统的工厂模式代码:
1. 定义一个抽象类Employee
```
public abstract class Employee {
protected String name;
protected int age;
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
public abstract void work();
}
```
2. 定义两个具体的员工类Manager和Developer,继承自Employee
```
public class Manager extends Employee {
public Manager(String name, int age) {
super(name, age);
}
@Override
public void work() {
System.out.println("Manager is managing employees.");
}
}
public class Developer extends Employee {
public Developer(String name, int age) {
super(name, age);
}
@Override
public void work() {
System.out.println("Developer is developing software.");
}
}
```
3. 定义一个EmployeeFactory类,根据传入的参数来创建对应的员工对象
```
public class EmployeeFactory {
public static final String MANAGER = "manager";
public static final String DEVELOPER = "developer";
public static Employee createEmployee(String type, String name, int age) {
if (type.equals(MANAGER)) {
return new Manager(name, age);
} else if (type.equals(DEVELOPER)) {
return new Developer(name, age);
} else {
throw new IllegalArgumentException("Invalid employee type.");
}
}
}
```
4. 在使用时,可以通过EmployeeFactory来创建对应类型的员工对象
```
public static void main(String[] args) {
Employee manager = EmployeeFactory.createEmployee(EmployeeFactory.MANAGER, "Tom", 35);
manager.work();
Employee developer = EmployeeFactory.createEmployee(EmployeeFactory.DEVELOPER, "Jerry", 25);
developer.work();
}
```
阅读全文
相关推荐


















