总公司和分公司
package org.ustc.composite;
public abstract class Company {
protected String companyName;
public Company(String companyName) {
super();
this.companyName = companyName;
}
public abstract void add(Company c);
public abstract void remove(Company c);
public abstract void display(int depth);
public abstract void duty();
}
package org.ustc.composite;
import java.util.ArrayList;
import java.util.List;
public class ConcreteCompany extends Company{
private List<Company> companys;
public ConcreteCompany(String companyName) {
super(companyName);
// TODO Auto-generated constructor stub
companys = new ArrayList<Company>();
}
@Override
public void add(Company c) {
// TODO Auto-generated method stub
companys.add(c);
}
@Override
public void remove(Company c) {
// TODO Auto-generated method stub
companys.remove(c);
}
@Override
public void duty() {
// TODO Auto-generated method stub
for(Company c:companys)
c.duty();
}
@Override
public void display(int depth) {
// TODO Auto-generated method stub
for(int i=0;i<depth;i++){
System.out.print("-");
}
System.out.println(this.companyName);
for(Company c:companys){
c.display(depth+2);
}
}
}
package org.ustc.composite;
public class HResourceDepartment extends Company{
public HResourceDepartment(String companyName) {
super(companyName);
// TODO Auto-generated constructor stub
}
@Override
public void add(Company c) {
// TODO Auto-generated method stub
}
@Override
public void remove(Company c) {
// TODO Auto-generated method stub
}
@Override
public void display(int depth) {
// TODO Auto-generated method stub
for(int i=0;i<depth;i++)
System.out.print("-");
System.out.println(this.companyName);
}
@Override
public void duty() {
// TODO Auto-generated method stub
System.out.println("培训员工");
}
}
package org.ustc.composite;
public class FinanceDepartment extends Company {
public FinanceDepartment(String companyName) {
super(companyName);
// TODO Auto-generated constructor stub
}
@Override
public void add(Company c) {
// TODO Auto-generated method stub
}
@Override
public void remove(Company c) {
// TODO Auto-generated method stub
}
@Override
public void display(int depth) {
// TODO Auto-generated method stub
for(int i=0;i<depth;i++)
System.out.print("-");
System.out.println(companyName);
}
@Override
public void duty() {
// TODO Auto-generated method stub
System.out.println("处理财务");
}
}
package org.ustc.composite;
public class Main {
public static void main(String[] args) {
Company root = new ConcreteCompany("北京总公司");
root.add(new FinanceDepartment("总公司财务部"));
root.add(new HResourceDepartment("总公司人力资源部"));
Company eastern = new ConcreteCompany("华东公司");
Company Nanjing = new ConcreteCompany("南京办事处");
eastern.add(Nanjing);
Nanjing.add(new FinanceDepartment("南京办事处人力资源"));
root.add(eastern);
root.display(1);
}
}