定义 :Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and cpmpositions of objects uniformly
将对象组合成树形结构以表示‘部分整体’ 层次结构 ,是的用户对单个对象和组合对象有一致性
自己写了一个例子 感觉很不恰当
组合模式有两种情况 ,透明的组合模式,和安全的组合模式。
透明的组合模式就是把composite中的属性和方法抽象到 Component 中 ,这样会有些问题,比如 left 节点会包含很多无用的数据和方法 。但这有一个好处就是对 场景类来说所有的对象,无论是单个对象还是组合对象的处理都相同,这样满足依赖倒置原则,也很好的利用多台机制。 另外一种方法就是 安全方法 ,这个方法使实现类与抽象类接口不同,不过这样会违反依赖倒置等原则。 需要注意 。。。
下面是一个例子
http://wenku.baidu.com/view/3bf40c1614791711cc7917e3.html
我自己写的一个。
package Composite; import java.util.ArrayList; public class Branch extends Corp{ ArrayList<Corp> list=new ArrayList<Corp>(); public Branch(String name, int salary, String position) { super(name, salary, position);
root 10000 manager xiaotoumu 5000 xiaotoumu xiaotoumu 5000 xiaotoumu xiaodi2 3000 xiaodi2 xiaodi 4000 xiaodi
}public void addElements(Corp c){list.add(c);} public ArrayList<Corp> getElements(){ return list; } }
package Composite;
import java.util.ArrayList;
public class Branch extends Corp{
ArrayList<Corp> list=new ArrayList<Corp>();
public Branch(String name, int salary, String position) {
super(name, salary, position);
}
public void addElements(Corp c){
list.add(c);
}
public ArrayList<Corp> getElements(){
return list;
}
}
package Composite;
import java.util.ArrayList;
public class Branch extends Corp{
ArrayList<Corp> list=new ArrayList<Corp>();
public Branch(String name, int salary, String position) {
super(name, salary, position);
}
public void addElements(Corp c){
list.add(c);
}
public ArrayList<Corp> getElements(){
return list;
}
}
package Composite;
import java.util.ArrayList;
public class Client {
public static String getTreeInfo(Branch b){
ArrayList<Corp> list =b.getElements();
String info=b.getInfo()+"\n";
for(Corp c:list){
if(c instanceof Leaf)
info=info+c.getInfo()+"\n";
else
info=info+c.getInfo()+"\n"+getTreeInfo((Branch)c);
}
return info;
}
public static void main(String []args){
Branch root=new Branch("root",10000,"manager");
Branch xiaotoumu=new Branch("xiaotoumu",5000,"xiaotoumu");
Leaf xiaod1=new Leaf("xiaodi",4000,"xiaodi");
Leaf xiaod2=new Leaf("xiaodi2",3000,"xiaodi2");
root.addElements(xiaotoumu);
xiaotoumu.addElements(xiaod2);
xiaotoumu.addElements(xiaod1);
System.out.println(Client.getTreeInfo(root));
}
}
可以看到,这个是安全模式下的组合模式,Client 知道了太多关于具体类实现的事情,违反了面向接口编程的约定。
我们在项目中应该 根据需求来合理选择