简单工厂设计模式
简单工厂设计模式: 解决集中创建对象的问题就称为简单工厂设计模式。
优点:当子类没有确定:类名、参数频繁变化的时候,只需要修改工厂类一处即可,整个改动是最少的
步骤:
1.属性的封装:
定义各个类的私有属性,设计getXXX()和setXXX()方法
private String name;
private String address;
private int id;
private char sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
2.各个类中添加构造函数
//员工类
public class Employee {
public Employee() {
}
public Employee(String name,String address,int id,char sex) {
this.name = name;
this.address = address;
this.id = id;
this.sex = sex;
}
}
//Pg员工类
public class PgEmployee extends Employee{
private int bugNumber;
public PgEmployee() {
}
public PgEmployee(String name,String address,int id,char sex,int bugNumber) {
super(name,address,id,sex);
this.bugNumber = bugNumber;
}
}
//Se员工类
public class SeEmployee extends Employee {
private int designNumber;
public SeEmployee() {
}
public SeEmployee(String name, String address, int id, char sex, int designNuber) {
super(name,address,id,sex);
this.designNumber = designNuber;
}
}
3.创建一个工厂类xxxFactory
public class EmployeeFactory {
public static Employee createEmployee(String name, String address, int id, char sex, int designNuber,int bugNumber,char type) {
Employee employee = null;
switch (type) {
case 'P':
employee = new PgEmployee(name, address, id, sex, bugNumber);
break;
case 'S':
employee = new SeEmployee(name, address, id, sex, designNuber);
break;
}
return employee;
}
}
4.在工厂类中 编写创建对象的方法:
- 1、方法的返回值是父类类型
- 2、方法的参数,包括所有子类需要的所有参数,额外 char type:创建哪个子类对象
- 3、判断类型,创建对象
- 4、返回父类类型
5.main方法
public class Test01 {
public static void main(String[] args) {
Employee[] employees = new Employee[10];
Employee pgEmployee = EmployeeFactory.createEmployee("张三", "山西", 123, '男', 0, 6, 'P');
Employee seEmployee = EmployeeFactory.createEmployee("李四", "陕西", 456, '女', 8, 0, 'S');
Ceo ceo = new Ceo();
employees[0] = pgEmployee;
employees[1] = seEmployee;
for (Employee employee : employees) {
if (employee != null) {
if (employee instanceof PgEmployee) {
//如果是PgEmployee类,将父类强转为子类
PgEmployee pgEmployee1 = (PgEmployee)employee;
ceo.listen(pgEmployee);
System.out.println("工号:"+pgEmployee1.getId()+",姓名:"+pgEmployee1.getName()+",住址"+pgEmployee1.getAddress()+",性别"+pgEmployee1.getSex()+",bug数量:"+pgEmployee1.getBugNumber());
}else if (employee instanceof SeEmployee) {
SeEmployee seEmployee1 = (SeEmployee)employee;
ceo.listen(seEmployee);
System.out.println("工号:"+seEmployee1.getId()+",姓名:"+seEmployee1.getName()+",住址"+seEmployee1.getAddress()+",性别"+seEmployee1.getSex()+",设计数量"+seEmployee1.getDesignNumber());
}
}
}
}
}