UML
公司抽象类
public abstract class Company {
protected String name;
public Company(String name) {
this.name = name;
}
public abstract void add(Company company);
public abstract void remove(Company company);
public abstract void display(int depth);
protected String getDepth(int depth) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < depth; i++) {
stringBuilder.append('-');
}
return stringBuilder.toString();
}
public abstract void invoke();
}
具体公司
import java.util.ArrayList;
import java.util.List;
public class ConcreteCompany extends Company {
private List<Company> companies = new ArrayList<>();
public ConcreteCompany(String name) {
super(name);
}
@Override
public void add(Company company) {
companies.add(company);
}
@Override
public void remove(Company company) {
companies.remove(company);
}
@Override
public void display(int depth) {
System.out.println(getDepth(depth) + name);
for (Company company : companies) {
company.display(depth + 2);
}
}
@Override
public void invoke() {
for (Company company : companies) {
company.invoke();
}
}
}
两个部门
public class HRDepartment extends Company {
public HRDepartment(String name) {
super(name);
}
@Override
public void add(Company company) {
}
@Override
public void remove(Company company) {
}
@Override
public void display(int depth) {
System.out.println(getDepth(depth) + name);
}
@Override
public void invoke() {
System.out.println(name + " 履行HR部门的职责");
}
}
public class FinanceDepartment extends Company {
public FinanceDepartment(String name) {
super(name);
}
@Override
public void add(Company company) {
}
@Override
public void remove(Company company) {
}
@Override
public void display(int depth) {
System.out.println(getDepth(depth) + name);
}
@Override
public void invoke() {
System.out.println(name +" 履行财务部门的职责");
}
}
测试类
public class Main {
public static void main(String[] args) {
ConcreteCompany root = new ConcreteCompany("北京百度总公司");
root.add(new HRDepartment("北京人力资源部"));
root.add(new FinanceDepartment("北京财务部"));
ConcreteCompany concreteCompany = new ConcreteCompany("山东济南分公司");
concreteCompany.add(new HRDepartment("济南人力资源部"));
concreteCompany.add(new FinanceDepartment("济南财务部"));
root.add(concreteCompany);
root.display(1);
root.invoke();
}
}
运行结果