【设计模式】组合模式
来源:互联网 发布:我国加工贸易数据 编辑:程序博客网 时间:2024/04/27 22:36
定义:允许你讲对象组合成树的形式结构来表现整体与部分的层次结构。
用途:组合能让客户以一直的方式处理个别对象以及对象组
UML图
Component:
抽象类(接口)定义了4个方法(上图不全)1 add添加一个Component 2 remove删除一个Component 3 取一个Compoent对象 4 功能方法
Leaf:
Extend于Component 主要实现了功能方法
Composit
Extend于Component、实现了Component的四个方法
Composit中有一个list集合用来盛放Component类型的对象、也就是Leaf和Composit、添加、删除、提取某个、这三个方法都是对Leaf的操作。
实现了功能方法、这里不同、他不仅实现了自己的功能、用Iterator遍历了调用了所有枝叶的功能方法。
当添加了一个Composit的对象时候、那个对象同样也能添加Leaf和Composit的对象、也就形成了树形结构、(Leaf可以添加多个)
代码
//抽象类Componentpublic abstract class Component {//添加分支public void add(Component component) {//没有实现接口或抽象类要求的方法时,抛出异常throw new UnsupportedOperationException();}//删除分支public void remove(Component component){throw new UnsupportedOperationException();}//取得某个组件public Component getChild(int i){throw new UnsupportedOperationException();}//输出自己的名字public void print(){throw new UnsupportedOperationException();}}
import java.util.ArrayList;import java.util.Iterator;public class Composite extends Component{//new一个Component类型的CompositeList、这样叶子节点和分叉都能加进来ArrayList<Component> compositeList =new ArrayList<Component>();String name;//构造方法添加名字public Composite(String name){this.name=name;}//添加分支实现public void add(Component component) {compositeList.add(component);}//删除分支实现public void remove(Component component){compositeList.remove(component);}//取得某个组件实现public Component getChild(int i){return (Component)compositeList.get(i);}//输出名字public String getName(){return name;}//输出自己的名字实现/遍历叶子与树枝public void print(){System.out.print(getName());throw new UnsupportedOperationException();//通过实现Iterator接口实现迭代每个分叉中的叶子与分叉Iterator iterator = compositeList.iterator();while(iterator.hasNext()){Component component=(Component)iterator.next();component.print();}}}
//叶子类public class Leaf extends Component{String name;//输入名字public Leaf(String name){this.name= name;}//输出名字public String getName(){return name;}}
//客户端使用public class test {public static void main(String args[]){//分支与叶子实例化Component compositeOne =new Leaf("根1");Component compositeTwo =new Leaf("根2");Component leafOne =new Leaf("叶子1");Component leafTwo =new Leaf("叶子2");compositeOne.add(compositeTwo);//根1添加一个分支compositeOne.add(leafOne);//根1添加一个叶子compositeTwo.add(leafTwo);//根2添加一个叶子compositeOne.print();//输出打印}}
考点:
抽象类关键字
继承关键字
组合关系
迭代器(应该不会考吧- -)
——————————最近貌似写博客遇到瓶颈了——————————
————————chenchen————————
0 0
- 设计模式:组合模式
- 设计模式-----组合模式
- 设计模式 组合模式
- 设计模式--组合模式
- 设计模式---组合模式
- 【设计模式】组合模式
- 设计模式 - 组合模式
- 设计模式----组合模式
- 设计模式 - 组合模式
- 设计模式:组合模式
- 设计模式 - 组合模式
- 设计模式-组合模式
- 设计模式 - 组合模式
- 【设计模式】组合模式
- 设计模式--组合模式
- 设计模式-组合模式
- 设计模式:组合模式
- 设计模式-----组合模式
- 秀技能:倒立及其他没用的
- oracle中如何查看一个方案中已经存在的sequence?
- 常见的安全攻击方式及防御简介
- Yii 获得当前控制器和方法
- ios svn repository
- 【设计模式】组合模式
- Android编程心得-FragmentActivity与Fragment两者交互方法简介
- POJ3299解题报告
- java 工程获取路径 web根目录。 项目classpath根目录 各种实用方法
- 电信运营商行业软件维护工作梳理
- CodeForces 479 E. Riding in a Lift
- windows计划任务后台定时执行java的jar文件
- 管理经验(二)——项目管理基础
- 【Cocos2d-x3.0学习笔记 01】熟悉的环境搭建