技术开发 频道

组合模式:实战人事管理之树状结构

  组合模式的重点就在树枝构件,其通用代码如代码清单21-19所示。

  代码清单21-19 树枝构件

public class Composite extends Component {
    
//构件容器
    private ArrayList<Component> componentArrayList = new ArrayList<Component>();
    
//增加一个叶子构件或树枝构件
    public void add(Component component){
        
this.componentArrayList.add(component);
    }
    
//删除一个叶子构件或树枝构件
    public void remove(Component component){
        
this.componentArrayList.remove(component);
    }
    
//获得分支下的所有叶子构件和树枝构件
    public ArrayList<Component> getChildren(){
        
return this.componentArrayList;
    }
}

  树叶节点是没有子下级对象的对象,定义参加组合的原始对象行为,其通用源代码如代码清单21-20所示。

  代码清单21-20 树叶构件

public class Leaf extends Component {
    
/*
     * 可以覆写父类方法
     * public void doSomething(){
     *
     * }
    
*/
}

  场景类负责树状结构的建立,并可以通过递归方式遍历整个树,如代码清单21-21所示。

  代码清单21-1 场景类

public class Client {

    
public static void main(String[] args) {
        
//创建一个根节点
        Composite root = new Composite();
        root.doSomething();
        
//创建一个树枝构件
        Composite branch = new Composite();
        
//创建一个叶子节点
        Leaf leaf = new Leaf();
        
//建立整体
        root.add(branch);
        branch.add(leaf);        
    }
    
//通过递归遍历树
    public static void display(Composite root){

        
for(Component c:root.getChildren()){
            
if(c instanceof Leaf){ //叶子节点
                c.doSomething();
            }
else{ //树枝节点
                display((Composite)c);
            }
        }
    }
}

  各位可能已经看出一些问题了,组合模式是对依赖倒转原则的破坏,但是它还有其他类型的变形,面向对象就是这么多的形态和变化,请读者继续阅读下去,就会找到解决方案。

0
相关文章