java中23种设计模式之13-组合模式(composite pattern)
import java.util.LinkedList;
abstract class Company
{
private String name;
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
abstract void add(Company company);
abstract void remove(Company company);
abstract void disp(int depth);
}
class Office extends Company
{
public Office(String name)
{
setName(name);
}
public void add(Company company)
{
System.out.println("office can not add");
}
public void remove(Company company)
{
System.out.println("office can not remove");
}
public void disp(int depth)
{
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < depth; i++) {
sb.append("-");
}
System.out.println(new String(sb) + this.getName());
//System.out.println("office name is: "+name);
}
}
class ConcreteCompany extends Company
{
public ConcreteCompany(String name)
{
setName(name);
}
LinkedList<Company> aCompanyList=new LinkedList<Company>();
public void add(Company company)
{
aCompanyList.add(company);
System.out.println("add office:"+company.getName());
}
public void remove(Company company)
{
aCompanyList.remove(company);
System.out.println("remove office:"+company.getName());
}
public void disp(int depth)
{
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < depth; i++) {
sb.append("-");
}
System.out.println(new String(sb) + this.getName());
for(Company company:aCompanyList)
{
company.disp(depth + 2);
}
}
}
public class CompositePatternTest
{
public static void main(String[] args)
{
Company parentCompany=new ConcreteCompany("安徽总公司");
Company suzhouBranchCompany=new ConcreteCompany("宿州分公司");
Company bengbuBranchCompany=new ConcreteCompany("蚌埠分公司");
Company hefeiOffice=new Office("合肥办事处");
parentCompany.add(suzhouBranchCompany);
parentCompany.add(bengbuBranchCompany);
parentCompany.add(hefeiOffice);
Company lingbiBranchCompany=new ConcreteCompany("灵璧分公司");
Company sixianOffice=new Office("泗县办事处");
Company huaiyuanOffice=new Office("怀远办事处");
Company dangshanOffice=new Office("砀山办事处");
suzhouBranchCompany.add(lingbiBranchCompany);
suzhouBranchCompany.add(sixianOffice);
suzhouBranchCompany.add(huaiyuanOffice);
suzhouBranchCompany.add(dangshanOffice);
Company louzhuangOffice=new Office("娄庄办事处");
lingbiBranchCompany.add(louzhuangOffice);
Company wuheOffice=new Office("五河办事处");
Company guzhenOffice=new Office("固镇办事处");
bengbuBranchCompany.add(wuheOffice);
bengbuBranchCompany.add(guzhenOffice);
parentCompany.disp(0);
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。