1、问题描述
小明所在的公司内部有多个部门,每个部门下可能有不同的子部门或者员工。
请你设计一个组合模式来管理这些部门和员工,实现对公司组织结构的统一操作。部门和员工都具有一个通用的接口,可以获取他们的名称以及展示公司组织结构。
输入示例
MyCompany
8
D HR
E HRManager
D Finance
E AccountantA
E AccountantB
D IT
E DeveloperA
E DeveloperB
输出示例
Company Structure:
MyCompany
HR
HRManager
Finance
AccountantA
AccountantB
IT
DeveloperA
DeveloperB
2、组合模式
它将对象组合成树状结构来表示“部分-整体”的层次关系。组合模式使得客户端可
以统⼀处理单个对象和对象的组合,⽽⽆需区分它们的具体类型。
类似树形结构,能够通过树形结构获取树中所有节点的信息。所有节点都有实现相同的接口
3、代码
import com.sun.java.accessibility.util.TopLevelWindowListener;
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
String companyName=sc.nextLine();
int number=Integer.parseInt(sc.nextLine());
Company company=new Company(companyName);
Department department=null;
for(int i=0;i<number;i++){
String s=sc.nextLine();
String[] s1=s.split(" ");
String a=s1[0];
String b=s1[1];
if(a.equals("D")){
department=new Department(b);
company.addDepartment(department);
}else if(a.equals("E")){
department.addEmployee(new Employee(b));
}
}
company.Display(0);
}
}
interface Component{
void Display(int depth);
}
class Employee implements Component{
private String name;
public Employee(String name){
this.name=name;
}
@Override
public void Display(int depth) {
for(int i=0;i<depth;i++){
System.out.print(" ");
}
System.out.println(this.name);
}
}
class Department implements Component{
List<Department> subDepartment;
List<Employee> employees;
String departmentName;
public Department(String name){
subDepartment=new ArrayList<>();
employees=new ArrayList<>();
departmentName=name;
}
public void addEmployee(Employee e){
employees.add(e);
}
public void addSubDepartment(Department d){
subDepartment.add(d);
}
@Override
public void Display(int depth) {
for(int i=0;i<depth;i++){
System.out.print(" ");
}
System.out.println(""+this.departmentName);
if(!subDepartment.isEmpty()){
for(int i=0;i<subDepartment.size();i++){
subDepartment.get(i).Display(depth+1);
}
}
if(!employees.isEmpty()){
for(int i=0;i<employees.size();i++){
employees.get(i).Display(depth+1);
}
}
}
}
class Company implements Component{
private String name;
List<Department> departments;
public Company(String name){
this.name=name;
departments=new ArrayList<>();
}
@Override
public void Display(int depth) {
System.out.println("Company Structure:");
System.out.println(this.name);
if(!departments.isEmpty()){
for(int i=0;i<departments.size();i++){
departments.get(i).Display(depth+1);
}
}
}
public void addDepartment(Department d){
departments.add(d);
}
}