主要目的,练习多态性,异常处理,设计模式
创建bean包,包含基础对象
创建员工类
package bean;
public class Employee {
private int id;
private String name;
private int age;
private double salary;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public Employee() {
super();
}
public Employee(int id, String name, int age, double salary) {
super();
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
public String getBasicInfo() {
return id + "\t" + name + "\t" + age + "\t" + salary;
}
@Override
public String toString() {
return id + "\t" + name + "\t" + age + "\t" + salary;
}
}
创建程序员类继承员工类
package bean;
public class Programmer extends Employee{
private int teamID;
private Status status = Status.FREE;
private Equipment equipment;
public Programmer() {
super();
}
public Programmer(int id, String name, int age, double salary,Equipment equipment) {
super(id,name,age,salary);
this.equipment = equipment;
}
public int getTeamID() {
return teamID;
}
public void setTeamID(int teamID) {
this.teamID = teamID;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public Equipment getEquipment() {
return equipment;
}
public void setEquipment(Equipment equipment) {
this.equipment = equipment;
}
@Override
public String toString() {
return super.getBasicInfo() + "\t程序员\t" + status.getSTATUS()+ "\t\t\t" + equipment.getEquipmentsInfo();
}
public String getInfo() {
return super.getBasicInfo() + "\t程序员\t";
}
}
创建设计师类继承程序员
package bean;
public class Designer extends Programmer {
private double Bouns;
public Designer() {
super();
}
public Designer(int id, String name, int age, double salary, Equipment equipment, double bouns) {
super(id, name, age, salary, equipment);
Bouns = bouns;
}
public double getBouns() {
return Bouns;
}
public void setBouns(double bouns) {
Bouns = bouns;
}
@Override
public String toString() {
return super.getBasicInfo() + "\t设计师\t" + getStatus().getSTATUS() + "\t" + Bouns + "\t\t" + getEquipment().getEquipmentsInfo();
}
@Override
public String getInfo() {
return super.getBasicInfo() + "\t设计师\t" + Bouns;
}
}
创建架构师类继承设计师
package bean;
public class Architect extends Designer {
private int stock;
public Architect() {
super();
}
public Architect(int id, String name, int age, double salary, Equipment equipment, double bouns, int stock) {
super(id, name, age, salary, equipment, bouns);
this.stock = stock;
}
public int getStock() {
return stock;
}
public void setStock(int stock) {
this.stock = stock;
}
@Override
public String toString() {
return super.getBasicInfo() + "\t架构师\t" + getStatus().getSTATUS() + "\t" + getBouns() + "\t" + stock + "\t" + getEquipment().getEquipmentsInfo();
}
@Override
public String getInfo() {
return super.getBasicInfo() + "\t架构师\t" + getBouns() + "\t" + stock;
}
}
创建设备接口
package bean;
//Equipment接口也可以定义为一个抽象类
public interface Equipment {
public abstract String getEquipmentsInfo();//获取设备信息的抽象方法
}
创建三种设备类,实现接口
台式机
package bean;
public class PC implements Equipment{
private String modle;//PC型号
private String display;//PC显示器型号
public PC() {
super();
}
public PC(String modle, String display) {
super();
this.modle = modle;
this.display = display;
}
public String getModle() {
return modle;
}
public void setModle(String modle) {
this.modle = modle;
}
public String getDisplay() {
return display;
}
public void setDisplay(String display) {
this.display = display;
}
@Override
public String getEquipmentsInfo() {
return modle + "(" + display + ")";
}
}
笔记本
package bean;
public class NoteBook implements Equipment {
private String modle;//笔记本型号
private double price;//笔记本价格
public String getModle() {
return modle;
}
public void setModle(String modle) {
this.modle = modle;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public NoteBook() {
super();
}
public NoteBook(String modle, double price) {
super();
this.modle = modle;
this.price = price;
}
@Override
public String getEquipmentsInfo() {
return modle + "(" + price + ")";
}
}
打印机
package bean;
//员工状态
//第一种类似单例模式的写法
public class Status {
private final String STATUS;
public static final Status FREE = new Status("FREE");
public static final Status BUSY = new Status("BUSY");
public static final Status VACATION = new Status("VACATION");
//私有构造器,通过构造器形参给STATUS赋值。
private Status(String status) {
this.STATUS = status;
}
//获取状态,返回String类型数据
public String getSTATUS() {
return STATUS;
}
}
//枚举类写法
//public class Status {
// private final String NAME;
// private Status(String name) {
// this.NAME = name;
// }
// public static final Status FREE = new Status("FREE");
// public static final Status VOCATION = new Status("VOCATION");
// public static final Status BUSY = new Status("BUSY");
// public String getNAME() {
// return NAME;
// }
// @Override
// public String toString() {
// return NAME;
// }
//}
创建工具类包:包含数据源与键盘交互工具
数据源
package util;
public class Data {
public static final int EMPLOYEE = 10;
public static final int PROGRAMMER = 11;
public static final int DESIGNER = 12;
public static final int ARCHITECT = 13;
public static final int PC = 21;
public static final int NOTEBOOK = 22;
public static final int PRINTER = 23;
//Employee : 10, id, name, age, salary
//Programmer: 11, id, name, age, salary
//Designer : 12, id, name, age, salary, bonus
//Architect : 13, id, name, age, salary, bonus, stock
public static final String[][] EMPLOYEES = {
{
"10", "1", "马云", "22", "3000"},
{
"13", "2", "马化腾", "32", "18000", "15000", "2000"},
{
"11", "3", "李彦宏", "23", "7000"},
{
"11", "4", "刘强东", "24", "7300"},
{
"12", "5", "雷军", "28", "10000", "5000"},
{
"11", "6", "任志强", "22", "6800"},
{
"12", "7", "柳传志", "29", "10800","5200"},
{
"13", "8", "杨元庆", "30", "19800", "15000", "2500"},
{
"12", "9", "史玉柱", "26", "9800", "5500"},
{
"11", "10", "丁磊", "21", "6600"},
{
"11", "11", "张朝阳", "25", "7100"},
{
"12", "12", "杨致远", "27", "9600", "4800"}
};
//如下的EQUIPMENTS数组与上面的EMPLOYEES数组元素一一对应
//PC :21, model, display
//NoteBook:22, model, price
//Printer :23, name, type
public static final String[][] EQUIPMENTS = {
{
},
{
"22", "联想T4", "6000"},
{
"21", "戴尔", "NEC17寸"},
{
"21", "戴尔", "三星 17寸"},
{
"23", "佳能 2900", "激光"},
{
"21", "华硕", "三星 17寸"},
{
"21", "华硕", "三星 17寸"},
{
"23", "爱普生20K", "针式"},
{
"22", "惠普m6", "5800"},
{
"21", "戴尔", "NEC 17寸"},
{
"21", "华硕","三星 17寸"},
{
"22", "惠普m6", "5800"}
};
}
工具类
package util;
import java.util.*;
/**
*
* @Description 项目中提供了TSUtility.java类,可用来方便地实现键盘访问。
* @author shkstart Email:[email protected]
* @version
* @date 2019年2月12日上午12:02:58
*
*/
public class TSUtility {
private static Scanner scanner = new Scanner(System.in);
/**
*
* @Description 该方法读取键盘,如果用户键入’1’-’4’中的任意字符,则方法返回。返回值为用户键入字符。
* @author shkstart
* @date 2019年2月12日上午12:03:30
* @return
*/
public static char readMenuSelection() {
char c;
for (; ; ) {
String str = readKeyBoard(1, false);
c = str.charAt(0);
if (c != '1' && c != '2' &&
c != '3' && c != '4') {
System.out.print("选择错误,请重新输入:");
} else break;
}
return c;
}
/**
*
* @Description 该方法提示并等待,直到用户按回车键后返回。
* @author shkstart
* @date 2019年2月12日上午12:03:50
*/
public static void readReturn() {
System.out.print("按回车键继续...");
readKeyBoard(100, true);
}
/**
*
* @Description 该方法从键盘读取一个长度不超过2位的整数,并将其作为方法的返回值。
* @author shkstart
* @date 2019年2月12日上午12:04:04
* @return
*/
public static int readInt() {
int n;
for (; ; ) {
String str = readKeyBoard(2, false);
try {
n = Integer.parseInt(str);
break;
} catch (NumberFormatException e) {
System.out.print("数字输入错误,请重新输入:");
}
}
return n;
}
/**
*
* @Description 从键盘读取‘Y’或’N’,并将其作为方法的返回值。
* @author shkstart
* @date 2019年2月12日上午12:04:45
* @return
*/
public static char readConfirmSelection() {
char c;
for (; ; ) {
String str = readKeyBoard(1, false).toUpperCase();
c = str.charAt(0);
if (c == 'Y' || c == 'N') {
break;
} else {
System.out.print("选择错误,请重新输入:");
}
}
return c;
}
private static String readKeyBoard(int limit, boolean blankReturn) {
String line = "";
while (scanner.hasNextLine()) {
line = scanner.nextLine();
if (line.length() == 0) {
if (blankReturn) return line;
else continue;
}
if (line.length() < 1 || line.length() > limit) {
System.out.print("输入长度(不大于" + limit + ")错误,请重新输入:");
continue;
}
break;
}
return line;
}
}
创建controller包,提供数组的具体操作方法
创建 EmployeeListService类,封装数据源到数组
package controller;
import bean.*;
import util.Data;
import static util.Data.*;//import static可以直接调取Data中的静态结构,不用再加Data.
//负责将Data中的数据封装到Employee[]数组中,同时提供相关操作Employee[]的方法。
public class EmployeeListService {
private Employee[] employeeList = new Employee[Data.EMPLOYEES.length];
//代码块中赋值
// {
// //创建设备数组,从Data中提取元素赋值
// Equipment[] equipments = new Equipment[Data.EQUIPMENTS.length];
// for (int i = 0; i < equipments.length; i++) {
// if(Data.EQUIPMENTS[i].length == 0) {
// continue;
// }
// switch(Data.EQUIPMENTS[i][0]) {
// case"21":
// equipments[i] = new PC(Data.EQUIPMENTS[i][1],Data.EQUIPMENTS[i][2]);
// break;
// case"22":
// equipments[i] = new NoteBook(Data.EQUIPMENTS[i][1],Double.parseDouble(Data.EQUIPMENTS[i][2]));
// break;
// case"23":
// equipments[i] = new Printer(Data.EQUIPMENTS[i][1],Data.EQUIPMENTS[i][2]);
// break;
// }
// }
// //从Data中提取元素给员工数组赋值赋值
// for (int i = 0; i < employeeList.length; i++) {
// switch(Data.EMPLOYEES[i][0]) {
// case "10":
// employeeList[i] = new Employee(Integer.parseInt(Data.EMPLOYEES[i][1]),Data.EMPLOYEES[i][2],Integer.parseInt(Data.EMPLOYEES[i][3]),Double.parseDouble(Data.EMPLOYEES[i][4]));
// break;
// case "11":
// employeeList[i] = new Programmer(Integer.parseInt(Data.EMPLOYEES[i][1]),Data.EMPLOYEES[i][2],Integer.parseInt(Data.EMPLOYEES[i][3]),Double.parseDouble(Data.EMPLOYEES[i][4]),equipments[i]);
// break;
// case "12":
// employeeList[i] = new Designer(Integer.parseInt(Data.EMPLOYEES[i][1]),Data.EMPLOYEES[i][2],Integer.parseInt(Data.EMPLOYEES[i][3]),Double.parseDouble(Data.EMPLOYEES[i][4]),equipments[i],Double.parseDouble(Data.EMPLOYEES[i][4]));
// break;
// case "13":
// employeeList[i] = new Architect(Integer.parseInt(Data.EMPLOYEES[i][1]),Data.EMPLOYEES[i][2],Integer.parseInt(Data.EMPLOYEES[i][3]),Double.parseDouble(Data.EMPLOYEES[i][4]),equipments[i],Double.parseDouble(Data.EMPLOYEES[i][4]),Integer.parseInt(Data.EMPLOYEES[i][5]));
// break;
// }
// }
// }
//构造器中赋值,创建员工数值,讲Data中的数据存入数组中
public EmployeeListService() {
for (int i = 0; i < employeeList.length; i++) {
int type = Integer.parseInt(EMPLOYEES[i][0]);
int id = Integer.parseInt(EMPLOYEES[i][1]);
String name = EMPLOYEES[i][2];
int age = Integer.parseInt(EMPLOYEES[i][3]);
double salary = Double.parseDouble(EMPLOYEES[i][4]);
Equipment equipment;
double bouns;
int stock;
switch(type) {
//根据员工类型调用相应的构造器,创建不同类型的对象以多态形式存入数组
case EMPLOYEE:
employeeList[i] = new Employee(id,name,age,salary);
break;
case PROGRAMMER:
equipment = getEquipment(i);
employeeList[i] = new Programmer(id,name,age,salary,equipment);
break;
case DESIGNER:
equipment = getEquipment(i);
bouns = Double.parseDouble(EMPLOYEES[i][5]);
employeeList[i] = new Designer(id,name,age,salary,equipment,bouns);
break;
case ARCHITECT:
equipment = getEquipment(i);
bouns = Double.parseDouble(EMPLOYEES[i][5]);
stock = Integer.parseInt(EMPLOYEES[i][6]);
employeeList[i] = new Architect(id,name,age,salary,equipment,bouns,stock);
break;
}
}
}
//获得设备对象匹配给员工
private Equipment getEquipment(int i) {
int type = Integer.parseInt(Data.EQUIPMENTS[i][0]);
switch(type) {
//根据设备类型不同,创建不同的对象
case PC:
return new PC(EQUIPMENTS[i][1],EQUIPMENTS[i][2]);
case NOTEBOOK:
return new NoteBook(EQUIPMENTS[i][1],Integer.parseInt(EQUIPMENTS[i][2]));
case PRINTER:
return new Printer(EQUIPMENTS[i][1],EQUIPMENTS[i][2]);
}
return null;
}
//获取员工数组
public Employee[] getAllEmployees() {
return this.employeeList;
}
//通过id获取员工对象
public Employee getEmployee(int id) throws TeamException{
for (int i = 0; i < employeeList.length; i++) {
if (employeeList[i].getId() == id) {
return employeeList[i];
}
}
throw new TeamException(id + "号员工不存在");
}
//打印所有员工信息
public void printEmployeeList() {
System.out.println("ID" + "\t" + "姓名" + "\t" + "年龄" + "\t" + "工资" + "\t" + "职位" + "\t" + "状态" + "\t" + "奖金" + "\t" + "股票" + "\t" + "装备");
for (int i = 0; i < employeeList.length; i++) {
System.out.println(employeeList[i]);
}
}
//打印空闲数组成员信息
public void printFreeEmployeeList() {
System.out.println("ID" + "\t" + "姓名" + "\t" + "年龄" + "\t" + "工资" + "\t" + "职位" + "\t" + "状态" + "\t" + "奖金" + "\t" + "股票" + "\t" + "装备");
for (int i = 0; i < employeeList.length; i++) {
if(employeeList[i] instanceof Programmer) {
//防止出现向下转型不成功的情况,普通员工无法加入团队
Programmer p = (Programmer)employeeList[i];
if(p.getStatus().getSTATUS().equalsIgnoreCase("free")) {
System.out.println(employeeList[i]);
}
}
}
}
//临时测试方法
public static void main(String[] args) {
EmployeeListService e = new EmployeeListService();
e.printEmployeeList();
System.out.println("--------------------");
Programmer[] p = new Programmer[EMPLOYEES.length-1];
for (int i = 0; i < p.length; i++) {
p[i] = (Programmer)e.employeeList[i+1];
System.out.println(p[i]);
}
}
}
创建TeamListService类
package controller;
import bean.*;
public class TeamListService {
private static int TeamID = 1;//团队编号赋值
private final int MAX_MEMBER =5;//最大成员
private Programmer[] team = new Programmer[MAX_MEMBER];//创建团队数组
private int total = 0;//记录成员人数
public int getTotal() {
return total;
}
public TeamListService() {
super();
}
//获取团队数组
public Programmer[] getTeam() {
Programmer[] team = new Programmer[total];
for (int i = 0; i < team.length; i++) {
team[i] = this.team[i];
}
return team;
}
//添加成员,考虑失败情况
public void addMember(Employee e) throws TeamException {
//成员已满,无法添加
if(total >= MAX_MEMBER) {
throw new TeamException("成员已满,无法添加");
}
//该成员不是开发人员,无法添加
if(!(e instanceof Programmer)) {
throw new TeamException("该成员不是开发人员,无法添加");
}
//该员工已在本开发团队中
if(isExist(e)) {
throw new TeamException("该员工已在本开发团队中");
}
//该员工已是某团队成员
Programmer p = (Programmer)e;
if(("BUSY".equals(p.getStatus().getSTATUS()))) {
//确定的字符串调用equals方法可以避免空指针异常
throw new TeamException("该员工已是某团队成员");
}
//该员正在休假,无法添加
if("VACATION".equalsIgnoreCase(p.getStatus().getSTATUS())) {
//equalsIgnoreCase忽略大小写进行比较
throw new TeamException("该员正在休假,无法添加");
}
//团队中至多只能有一名架构师
//团队中至多只能有两名设计师
//团队中至多只能有三名程序员
//遍历数组统计职业人数
int numberOfArchitect = 0,numberOfDesigner = 0,numberOfProgrammer = 0;
for (int i = 0; i < total; i++) {
if(team[i] instanceof Architect) {
//范围小的放在前面
numberOfArchitect++;
}else if(team[i] instanceof Designer) {
numberOfDesigner++;
}else {
numberOfProgrammer++;
}
}
//错误写法,如果team中没有一个架构师,想要添加一个,第一种情况不满足,就会进入下一个if语句中判断,第二种情况满足就会抛出异常。
//这样架构师无法添加成功
// if(e instanceof Architect && numberOfArchitect >= 1) {
// throw new TeamException("团队中至多只能有一名架构师");
// }else if(e instanceof Designer && numberOfDesigner >=2) {
// throw new TeamException("团队中至多只能有两名设计师");
// }else if(e instanceof Programmer && numberOfProgrammer >=3) {
// throw new TeamException("团队中至多只能有三名程序员");
// }
if(e instanceof Architect) {
if(numberOfArchitect >= 1) {
throw new TeamException("团队中至多只能有一名架构师");
}
}else if (e instanceof Designer) {
if(numberOfDesigner >= 2) {
throw new TeamException("团队中至多只能有两名设计师");
}
}else if(e instanceof Programmer){
if(numberOfProgrammer >= 3) {
throw new TeamException("团队中至多只能有三名程序员");
}
}
//排除以上情况后可以添加
team[total++] = p;
//修改成员状态
p.setStatus(Status.BUSY);
//添加TeamID
p.setTeamID(TeamID++);
}
//判断成员是否存在在团队中
private boolean isExist(Employee e) {
for (int i = 0; i < total; i++) {
if (team[i].getId() == e.getId()) {
return true;
}
}
return false;
}
//判断成员的是否在组中重载方法
private boolean isExist(int teamID) {
for (int i = 0; i < total; i++) {
if(team[i].getTeamID() == teamID) {
return true;
}
}
return false;
}
//删除团队成员方法
public void removeMember(int TeamID) throws TeamException {
if(total <= 0) {
throw new TeamException("团队中没有成员,无法删除");
}
if(!isExist(TeamID)) {
throw new TeamException("团队中不存在此成员,无法删除");
}
int i = 0;
for (; i < total; i++) {
if(isExist(TeamID)) {
team[i].setStatus(Status.FREE);
break;
}
}
//第二种写法,在此处抛出异常
// if(i == total) {
// throw new TeamException("团队中不存在此成员,无法删除");
// }
for(int j = i;j < total -1;j++) {
team[j] = team[j + 1];
}
team[--total] = null;
}
}
创建自定义异常类
package controller;
//创建自定义异常以供方法调用
public class TeamException extends Exception{
static final long serialVersionUID = 13678653435L;
public TeamException() {
super();
}
public TeamException(String message) {
super(message);
}
}
创建view包,提供方法界面
创建MainView类,配置界面,调取方法,实现功能
package view;
import java.util.Scanner;
import bean.*;
import controller.*;
import util.*;
public class MainView {
private EmployeeListService employeeListSvc = new EmployeeListService();
private TeamListService teamListSvc = new TeamListService();
public void enterMenu() {
boolean mark = true;
char choice = 0;
while(mark) {
if (choice != '1') {
System.out.println("------------------------------团队成员管理程序---------------------------------" + "\n");
listAllEmployees();
System.out.println("---------------------------------------------------------------------------");
}
System.out.println("1-团队列表 2-添加成员 3-删除成员 4-退出程序 请选择(1-4):");
choice = TSUtility.readMenuSelection();
switch (choice) {
case '1':
listTeamMember();
choice = 0;
TSUtility.readReturn();
break;
case '2':
System.out.println("--------------------------------空闲人员列表----------------------------------");
employeeListSvc.printFreeEmployeeList();
System.out.println("---------------------------------------------------------------------------");
System.out.println("请输入添加人员ID");
int i = TSUtility.readInt();
addMember(i);
TSUtility.readReturn();
break;
case '3':
listTeamMember();
System.out.println("请输入删除人员的TeamID");
int j = TSUtility.readInt();
System.out.println("请确认是否删除人员(Y/N)");
char confirmdelete = TSUtility.readConfirmSelection();
if(confirmdelete == 'Y') {
deleteMember(j);
}else {
System.out.println("取消删除");
}
TSUtility.readReturn();
break;
case '4':
System.out.println("请确认是否退出“Y/N”");
char confirmation = TSUtility.readConfirmSelection();
if (confirmation == 'Y') {
mark = false;
System.out.println("程序退出");
return;
}
break;
}
}
}
private void listAllEmployees() {
Employee[] e = employeeListSvc.getAllEmployees();
if(e == null || e.length == 0) {
System.out.println("公司没人了,老板跑路了,");
}
employeeListSvc.printEmployeeList();
}
private void listTeamMember() {
Programmer[] p = teamListSvc.getTeam();
if(p == null || p.length == 0) {
System.out.println("---目前还没有成员在项目组中,请先添加成员---");
}else {
System.out.println("---------------------------------------------------------------");
System.out.println("TID/ID" + "\t" + "姓名" + "\t" + "年龄" + "\t" + "工资" + "\t" + "职位" + "\t" + "奖金" + "\t" + "股票" );
for (int i = 0; i < teamListSvc.getTotal(); i++) {
System.out.println(p[i].getTeamID() + "/"+ p[i].getInfo());
}
System.out.println("---------------------------------------------------------------");
}
}
//添加团队成员,通过员工ID
private void addMember (int i) {
Employee employee = new Employee();
Employee[] p = employeeListSvc.getAllEmployees();
for (int j = 0; j < p.length; j++) {
if(p[j].getId() == i) {
employee = p[j];
}
}
try {
teamListSvc.addMember(employee);
System.out.println("添加成功");
} catch (TeamException e) {
// TODO Auto-generated catch block
System.out.println("添加失败" + e.getMessage());
}
}
//删除团队成员,通过团队编号
private void deleteMember (int i) {
try {
teamListSvc.removeMember(i);
System.out.println("删除成功");
} catch (TeamException e) {
// TODO Auto-generated catch block
System.out.println("删除失败" + e.getMessage());
}
}
//测试方法
public static void main(String[] args) {
MainView view = new MainView();
view.enterMenu();
}
}