posite)模式
场景问题
商品类别树
+服装
+男装
-衬衣
-夹克
+女装
-裙子
-套装
特点
有一个根节点
树枝节点
叶子节点
现在需要管理商品类别树,假设要求能实现输出如上商品类别树的结构功能,应该如何实现?
分析
商品类别树的节点被分成两种,一种是容器节点,另一种是叶子节点。
容器节点可以包含其他容器节点或者叶子节点
不带模式的解决方案
叶子对象:
public class Leaf{
private String name="";
public Leaf(String name){
=name;
}
public void printStruct(String preStr){
(preStr+"-"+name);
}
}
组合对象的代码实现
组合对象里可以包含其他组合对象或者是叶子对象,由于类型不同,需要分开记录
public posite {
private posite>posite=
new posite>();
private Collection<Leaf>childLeaf=
new ArrayList<Leaf>();
private String name="";
posite(String name){
=name;
}
public void posite c){
(c);
}
public void addLeaf(Leaf leaf){
(leaf);
}
public void printStruct(String preStr){
(preStr+"+"+);
preStr+=" ";
for(Leaf leaf:childLeaf){
(preStr);
}
posite c:posite){
(preStr);
}
}
}
客户端
public class Client {
public static void main(String[] args) {
\\定义所有的组合对象
Composite root=posite("服装");
Composite c1=posite("男装");
Composite c2=posite("女装");
\\定义所有的叶子节点
Leaf leaf1=new Leaf("衬衣");
Leaf leaf2=new Leaf("夹克");
Leaf leaf3=new Leaf("裙子");
Leaf leaf4=new Leaf("套装");
\\按照树的结构来组合组合对象和叶子对象
(c1);
(c2);
(leaf1);
(leaf2);
(leaf3);
(leaf4);
(" ");
}
}
有何问题
必须区分组合对象和叶子对象,并进行区别的对待
区别对待组合对象和叶子对象,不仅让程序变得复杂,还对功能的扩展也带来不便。
19 设计模式教学课件 来自淘豆网m.daumloan.com转载请标明出处.