您的位置:首页 > 编程语言 > Java开发

Java语言设计模式之组合模式(Composite)

2017-08-30 14:01 591 查看
实现 composite 模式的最简单的实例:

CompositeStructure .java

package com.enfo.wd.mode;

import java.util.ArrayList;
import java.util.Iterator;

interface Component{
void operation();
}
class Leaf implements Component{
private String name;
public Leaf(String name){this.name=name;}
public String toString(){return name;}
@Override
public void operation() {
System.out.println(this);
}
}
@SuppressWarnings({ "serial", "rawtypes" })
class Node extends ArrayList implements Component{
private String name;
public Node(String name){this.name=name;}
public String toString(){return name;}
@Override
public void operation() {
System.out.println(this);
for(Iterator it=iterator();it.hasNext();)
((Component)it.next()).operation();
}

}
public class CompositeStructure {
@SuppressWarnings("unchecked")
public void test(){
Node root=new Node("root");
root.add(new Leaf("Leaf1"));
Node c2 = new Node("Node1");
c2.add(new Leaf("Leaf2"));
c2.add(new Leaf("Leaf3"));
root.add(c2);
c2 = new Node("Node2");
c2.add(new Leaf("Leaf4"));
c2.add(new Leaf("Leaf5"));
root.add(c2);
root.operation();
}
public static void main(String[] args) {
CompositeStructure cp=new CompositeStructure();
cp.test();
}

}


这是实现 composite 模式的最简单的方法。当然这种方法在用于大型系统的时候可能会出现问题。但是,最好的做法可能就是从最简单的方法入手,而只在需要的时候才去改变它。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息