设计模式之组合模式
组合模式:将对象组合成树形结构以表示部分整体的层次结构(将叶子节点组合进枝干,枝干上也可以再生枝干,叶子上不可以生叶子,所以在写逻辑之前确定好那些是叶子哪些是枝干)。组合模式使得用户对单个对象的使用具有一致性。
什么时候使用组合模式呢?
当你发现需求中是体现部分与层次结构的时候及你希望用户可以忽略组合对象与单个对象的不同,统一的使用组合结构中的所有对象,就应该考虑--------来自大话设计模式
从下面的图可以得出leaf,composite都是component,这样就可以忽略单个对象和组合对象的不同。
UML图
//抽象接口提供公共的方法
public abstract class Component {
protected String name;
public Component(String name){
this.name=name;
}
public abstract void Add(Component c);
public abstract void Remove(String c);
public abstract void Display();
}
//财务部
public class Leaf extends Component {
public Leaf(String name) {
super(name);
}
@Override
public void Add(Component c) {
System.out.println("不可添加");
}
@Override
public void Remove(String c) {
System.out.println("不可删除");
}
@Override
public void Display() {
System.out.println(this.getClass().getName()+name);
}
}
//人力部
public class Leaf2 extends Component {
public Leaf2(String name) {
super(name);
}
@Override
public void Add(Component c) {
System.out.println("不可添加");
}
@Override
public void Remove(String c) {
System.out.println("不可删除");
}
@Override
public void Display() {
System.out.println(this.getClass().getName()+name);
}
}
//枝节点行为类
public class Composite extends Component{
//如果财务部、人力部和组合节点不同时继承那么就无法实现下面这个公用的带有泛型的集合
//也就是说让单个对象和组合对象具有一致性,他们都是Component
private List<Component> children = new ArrayList<Component>();
public Composite(String name) {
super(name);
}
@Override
public void Add(Component c) {
children.add(c);
}
@Override
public void Remove(String c) {
Iterator<Component> iterable = children.iterator();
while (iterable.hasNext()){
Component t = iterable.next();
if(c.equals(t.name)){
iterable.remove();
}
}
}
@Override
public void Display() {
System.out.println(this.getClass().getResource("/")+name);
for (Component c1:children) {
c1.Display();
}
}
}
//测试客户端
public class test {
public static void main(String[] args) {
//声明一个公司总部A
Composite composite = new Composite("西安总部");
//总部有财务部和人力部
composite.Add(new Leaf("总部的财务部"));
composite.Add(new Leaf2("总部的人力部"));
//上海分部
Composite shanghaicomposite = new Composite("上海分部");
//上海分部有财务部和人力部
shanghaicomposite.Add(new Leaf("上海分部的财务部"));
shanghaicomposite.Add(new Leaf2("上海分部的人力部"));
composite.Add(shanghaicomposite);
//北京分布
Composite beijingcomposite = new Composite("北京分部");
//北京分布有财务部和人力部
beijingcomposite.Add(new Leaf("北京分部的财务部"));
beijingcomposite.Add(new Leaf2("北京分部的人力部"));
composite.Add(beijingcomposite);
//查看
composite.Display();
//业务调整移除上海的人力部
System.out.println("============");
shanghaicomposite.Remove("上海分部的人力部");
//查看
composite.Display();
}
}