在本例子中,没有什么特殊之处,所不同的是Composite可以容纳Component的子类对象,包括本身。例子本省也比较简单,平淡无味,单却可以在特定的场景能很好的解决特定的问题。
使用组合模式有如下的好处:
l 定义了饱含基本对象和组合对象的类层次结构,基本对象可以被组合成更复杂的组合对象,而这个组合对象有可以被组合。
l 简化客户代码 客户可以一直地使用组合结构和单个对象,通常用户不知道处理的是一个叶节点还是一个组合组件。
l 使得更容易增加新类型的组件, 新定义的Composite或leaf子类自动地与义有的结构和客户代码一起工作,客户程序不需要因为新的Component类而改变。
l 使你的设计变得更一般化。
实现的代码:
Component接口:
package composite;
public interface Component{
public int getSize();
public int getChildNum();
public String getType();
public String getName();
public void add(Component c);
public void remove(Component c);
}
Leaf类:
package composite;
public class Leaf implements Component{
private int size;
private String name;
public Leaf(String aName,int aSize){
size = aSize;
name = aName;
}
public String getName(){
return name;
}
public String getType(){
return "Leaf";
}
public int getSize(){
return size;
}
public int getChildNum(){
return 1;
}
public void add(Component c){
System.err.println("Not supported method!");
}
public void remove(Component c){
System.err.println("Not supported method!");
}
}
Composite类:
package composite;
public class Composite implements Component{
private int size;
private String name;
public Composite(String aName,int aSize){
size = aSize;
name = aName;
}
public String getName(){
return name;
}
public String getType(){
return "Leaf";
}
public int getSize(){
return size;
}
public int getChildNum(){
return 1;
}
public void add(Component c){
System.err.println("Not supported method!");
}
public void remove(Component c){
System.err.println("Not supported method!");
}
}
客户端代码:
package composite;
public class Client{
public static void main(String[] args){
Component root = new Composite("root");
Component composite = new Composite("composite");
Component leaf1 = new Leaf("leaf1",20);
Component leaf2 = new Leaf("leaf2",40);
root.add(leaf1);
composite.add(leaf2);
root.add(composite);
String str = "Leaf1's size is "+leaf1.getSize();
str += "\nleaf2's size is " + leaf2.getSize();
str += "\nComposite's size is " + composite.getSize();
str += "\nRoot's size is " + root.getSize();
System.out.println(str);
}
}
总结:组合模式在 解决整体与部分 的问题中 应用比较广泛,一个组合也可以被看作 部分来处理,降低了处理问题的难度。
使用组合模式编写的实例
需积分: 16 190 浏览量
2011-06-10
15:38:04
上传
评论
收藏 16KB ZIP 举报
wff0317
- 粉丝: 0
- 资源: 2
最新资源
- 农村信用社联合社计算机信息系统投产与变更管理办.docx
- 农村信用社联合社计算机信息系统数据管理办法.docx
- 利用SPSS作临床效度分析线上计算网站介绍-医学研究部统计谘.(医学PPT课件).ppt
- 利用Zabbix监控mysqldump定时备份数据库状态.docx
- 利用计算机解决问题的基本过程.doc
- 化工铁路通信工程总结.doc
- 北京大学网络教育软件工程作业.docx
- 医药公司(连锁店)计算机操作规程未新系统的自行按照旧制修改-新系统过制的编号加修模版.doc
- 医药公司(连锁店)计算机系统操作规程模版.doc
- 医药连锁门店计算机系统的操作和管理程序未新系统的自行按照旧制修改-新系统过制的编号加修模版.docx
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈