1.题目: 有一个根节点,比如“服装”,它没有父节点,它可以包含其他的节点。 树枝节点,有一类节点可以包含其他的节点,称之为树枝节点,比如“男装”、“女装”和“母婴”。 叶子节点,有一类节点没有子节点,称之为叶子节点,比如“衬衣”、“夹克”、“裙子”、“套装”等。 如果碰到类似上面这种,需使用对象树来描述或实现的功能,都可以考虑使用组合模式,比如读取XML文件,或是对语句进行语法解析等。 2.UML图
3.代码
代码语言:javascript复制package 组合模式;
public abstract class Cloth {
protected String name;
public Cloth(String name)
{this.name=name;
}
public abstract void Add(Cloth c);
public abstract void Remove(Cloth c);
public abstract void display(String str);
}
代码语言:javascript复制package 组合模式;
import java.util.ArrayList;
public class ConcreteCloth extends Cloth {
private ArrayList<Cloth>children=new ArrayList<Cloth>();
public ConcreteCloth(String name)
{
super(name);
}
@Override
public void Add(Cloth c) {
children.add(c);
}
@Override
public void Remove(Cloth c) {
children.remove(c);
}
@Override
public void display(String str) {
str ="-";
System.out.println(str name);
for(Cloth component:children)
{component.display(str);
}
}
}
代码语言:javascript复制package 组合模式;
public class Custome extends Cloth {
public Custome(String name) {
super(name);
}
@Override
public void Add(Cloth c) {
}
@Override
public void Remove(Cloth c) {
}
@Override
public void display(String str) {
str ="-";
System.out.println(str name);
}
}
代码语言:javascript复制package 组合模式;
public class Jacket extends Cloth {
public Jacket(String name) {
super(name);
}
@Override
public void Add(Cloth c) {
}
@Override
public void Remove(Cloth c) {
}
@Override
public void display(String str) {
str ="-";
System.out.println(str name);
}
}
代码语言:javascript复制package 组合模式;
public class Shirt extends Cloth {
public Shirt(String name) {
super(name);
// TODO Auto-generated constructor stub
}
@Override
public void Add(Cloth c) {
// TODO Auto-generated method stub
}
@Override
public void Remove(Cloth c) {
// TODO Auto-generated method stub
}
@Override
public void display(String str) {
str ="-";
System.out.println(str name);
}
}
代码语言:javascript复制package 组合模式;
public class Skirt extends Cloth {
public Skirt(String name) {
super(name);
// TODO Auto-generated constructor stub
}
@Override
public void Add(Cloth c) {
// TODO Auto-generated method stub
}
@Override
public void Remove(Cloth c) {
// TODO Auto-generated method stub
}
@Override
public void display(String str) {
str ="-";
System.out.println(str name);
}
}
代码语言:javascript复制package 组合模式;
public class Test {
public static void main(String[] args) {
ConcreteCloth root=new ConcreteCloth("服装");
ConcreteCloth comp1=new ConcreteCloth("男装");
ConcreteCloth comp2=new ConcreteCloth("女装");
comp1.Add(new Shirt("衬衫"));
comp1.Add(new Jacket("夹克"));
comp2.Add(new Skirt("裙子"));
comp2.Add(new Custome("礼服"));
root.Add(comp1);
root.Add(comp2);
root.display("");
}
}