组合模式
2017-08-10 22:04 grows 阅读(145) 评论(0) 编辑 收藏 举报- 组合模式:
主要是解决整体与部分的问题,用户希望把从整体和部分之间的复杂的组合关系解放出来,把整合和部分看成一个东西所以就需要整体和部分使同一个接口
- 角色:
1) 整体:枝干
2) 部分:枝叶
3) 公共接口
- 代码实现
package component; /** * 公共接口 * @author Administrator * */ public interface ComponentInter { public String getName(); }
package component; /** *部分实现接口 * @author Administrator * */ public class Portion implements ComponentInter { private String name; Portion(String name){ System.out.println("部件"+name); this.name=name; } @Override public String getName() { // TODO Auto-generated method stub return name; } }
package component; import java.util.LinkedList; import java.util.List; /** * 整体部分,申明一个list可以保存各种部件 * @author Administrator * */ public class Whole implements ComponentInter { private String name; Whole(String name){ this.name=name; System.out.println("整体"+this.name); } private List<ComponentInter> components=new LinkedList<ComponentInter>(); @Override public String getName() { // TODO Auto-generated method stub return name; } public void addComponentInter(ComponentInter com){ System.out.println(this.name+"添加"+com.getName()); components.add(com); } public void removeComponentInter(ComponentInter com){ System.out.println(this.name+"删除"+com.getName()); components.remove(com); } }
package component; public class testComponent { public static void main(String[] args) { // TODO Auto-generated method stub ComponentInter leaf1=new Portion("螺丝钉"); ComponentInter leaf2=new Portion("螺丝帽"); ComponentInter leaf3=new Portion("木板"); Whole whole=new Whole("小车"); whole.addComponentInter(leaf1); whole.addComponentInter(leaf2); whole.addComponentInter(leaf3); whole.removeComponentInter(leaf3); } }
部件螺丝钉
部件螺丝帽
部件木板
整体小车
小车添加螺丝钉
小车添加螺丝帽
小车添加木板
小车删除木板
4.使用场景
适合处理整体和部分的问题