其中Company 为抽象类,定义了在组织结构图上添加(Add)和删除(Delete)分公司/办事处或者部门的方法接口。类ConcreteCompany表示具体的分公司或者办事处,分公司或办事处下可以设置不同的部门。类HRDepartment和FinanceDepartment 分别表示人力资源部和财务部。
代码如下:
package combinationmode;
//抽象构件类根节点
public abstract class Company {
protected String name;
public Company(String name) {
this.name= name;
}
abstract void add(Company c);
abstract void Delete(Company c);
abstract void show();
}
//树枝类
package combinationmode;
import java.util.ArrayList;
import java.util.List;
public class CompanyComposite extends Company{
private List<Company> children = new ArrayList<>();
public CompanyComposite(String name) {
super(name);
}
@Override
void add(Company c) {
children.add(c); //添加
}
@Override
void Delete(Company c) {
children.remove(c); //删除
}
@Override
void show() {
System.out.println(name);
}
public void ifi(){
for (Object child : children) {
((Company)child).show();
}
}
@Override
public String toString() {
return "CompanyComposite{" +
"children=" + children +
'}';
}
}
//树叶类,有两个树叶
package combinationmode;
public class HRLeaf extends Company{
public HRLeaf(String name) {
super(name);
}
@Override
public void add(Company c) {
}
@Override
public void Delete(Company c) {
}
@Override
public void show() {
System.out.println(name);
}
}
package combinationmode;
public class FinLeaf extends Company{
public FinLeaf(String name) {
super(name);
}
@Override
public void add(Company c) {
}
@Override
public void Delete(Company c) {
}
@Override
public void show() {
System.out.println(name);
}
}
//客户端类,把叶子和树枝加入容器输出
package combinationmode;
public class Client {
public static void main(String[] args) {
CompanyComposite c1,c2,c3,c4;
c1=new CompanyComposite("北京总公司");
c1.add(new HRLeaf("总公司人力资源部"));
c1.add(new FinLeaf("总公司财务部"));
c2=new CompanyComposite("上海分公司");
c1.add(c2);
c2.add(new HRLeaf("上海分公司人力资源部"));
c2.add(new FinLeaf("上海分公司财务部"));
c3=new CompanyComposite("南京办事处");
c2.add(c3);
c3.add(new HRLeaf("南京办事处人力资源部"));
c3.add(new FinLeaf("南京办事处财务部"));
c1.ifi();
c2.ifi();
c3.ifi();
}
}
输出结果: