介绍主要构成的几个角色实用举例抽象构件公司或者部门构构件(树枝)小组(子叶)测试代码测试结果
介绍组合模式又叫合成模式。有时候又叫部分-整体模式。主要用来描述描述部分和整体的关系。组要是以树形结构表示。
比如,一个公司下,有多个部门,每个部门下又有几个组别。这种至上而下分布。
Component抽象构件角色
这个抽象角色,包含着所有的觉得的共同点。包括一些方法和属性。Leaf叶子构件
子叶,一个结构的最小构成。ComPosite树枝构件
可以包含其他的数字和节点。
实例是有一个公司,公司下面有3个部门。其中1个部门还有小分组。就是说这三个部门中有两个部门是子叶对象, 另外的一个部门就是我们的树枝构件
抽象构件
public abstract class Component {
protected String description;
protected int parentId;
protected int id;
public abstract String description();
}
公司或者部门构构件(树枝)
public class Composite extends Component{
private List mComponents = new ArrayList<>();
public Composite(String description, int id, int parentId) {
this.description = description;
this.id = id;
this.parentId = parentId;
}
@Override
public String description() {
return description;
}
public void add(Component component) {
mComponents.add(component);
}
public void remove(Component component) {
mComponents.remove(component);
}
public List getComponents() {
return mComponents;
}
public boolean hasLeaf() {
return mComponents.size()>0;
}
}
小组(子叶)
public class Leaf extends Component{
public Leaf(String description, int id, int parentId) {
this.description = description;
this.id = id;
this.parentId = parentId;
}
@Override
public String description() {
return description;
}
}
测试代码
public static void main(String[] args) {
Composite company = new Composite("某公司", 1, 0);
Composite departmentOne = new Composite("部门1", 2, 1);
Composite departmentTwo = new Composite("部门2", 3, 1);
Composite departmentThree = new Composite("部门3", 4, 1);
company.add(departmentOne);
company.add(departmentTwo);
company.add(departmentThree);
Leaf leaf = new Leaf("部门小组", 5, 2);
departmentOne.add(leaf);
List components = company.getComponents();
if (components.size() > 0) {
System.out.println(company.description() + "有部门数量" + components.size());
}
//遍历构件
scan(components);
}
测试结果
某公司有部门数量3 部门1 部门小组 部门2 部门3
一起进步如果你觉得,我写的东西对你帮助,那我会觉得很开心。如果你觉得我写的东西还需要改进,我很想听到你的建议。让我们一起进步吧。 可以加入QQ群聊一起探讨:关注后可以获得联系方式。感谢您的支持。 做一个有态度的公众号



