设计模式(十二)——组合模式
2016-08-05 00:00
246 查看
摘要: 结构型模式
一、定义
将对象组合成树形结构的层次结构,树的节点或者整个结构对于调用者来说没有任何区别
二、要素
1.枝干和叶子节点的抽象类
2.枝干类
3.叶子节点类
三、代码实例
//节点和枝干抽象类
public abstract class Component {
public void doSomething(){
}
}
//枝干
public class Composite extends Component{
private ArrayList<Component> list = new ArrayList<Component>();
public void add(Component component){
list.add(component);
}
public ArrayList<Component> getChilds(){
return this.list;
}
}
//叶子节点
public class Leaf extends Component{
private String mValue;
public Leaf(String value){
this.mValue = value;
}
public void doSomething(){
System.out.print(this.mValue+"\n");
}
}
//客户端
public class Client {
public static void main(String[] args) {
Composite root = new Composite();
Composite branch = new Composite();//枝干
Component leftLeaf = new Leaf("左叶子节点");//左叶子节点
Component rightLeaf = new Leaf("右叶子节点");//右叶子节点
branch.add(leftLeaf);
branch.add(rightLeaf);
root.add(branch);
show(root);
}
public static void show(Composite root){
for(Component component : root.getChilds()){
if(component instanceof Leaf){
component.doSomething();
} else {
show((Composite)component);
}
}
}
}
四、说明
1.高层模块无需关心处理的是单个对象还是整个组合结构
2.枝干和叶子节点都很容易扩展,符合开闭原则
一、定义
将对象组合成树形结构的层次结构,树的节点或者整个结构对于调用者来说没有任何区别
二、要素
1.枝干和叶子节点的抽象类
2.枝干类
3.叶子节点类
三、代码实例
//节点和枝干抽象类
public abstract class Component {
public void doSomething(){
}
}
//枝干
public class Composite extends Component{
private ArrayList<Component> list = new ArrayList<Component>();
public void add(Component component){
list.add(component);
}
public ArrayList<Component> getChilds(){
return this.list;
}
}
//叶子节点
public class Leaf extends Component{
private String mValue;
public Leaf(String value){
this.mValue = value;
}
public void doSomething(){
System.out.print(this.mValue+"\n");
}
}
//客户端
public class Client {
public static void main(String[] args) {
Composite root = new Composite();
Composite branch = new Composite();//枝干
Component leftLeaf = new Leaf("左叶子节点");//左叶子节点
Component rightLeaf = new Leaf("右叶子节点");//右叶子节点
branch.add(leftLeaf);
branch.add(rightLeaf);
root.add(branch);
show(root);
}
public static void show(Composite root){
for(Component component : root.getChilds()){
if(component instanceof Leaf){
component.doSomething();
} else {
show((Composite)component);
}
}
}
}
四、说明
1.高层模块无需关心处理的是单个对象还是整个组合结构
2.枝干和叶子节点都很容易扩展,符合开闭原则
相关文章推荐
- 设计模式 (十二)组合模式(Composite)
- 设计模式十二(组合模式,python语言实现)
- 设计模式 (十二)组合模式(Composite)
- 设计模式 (十二)组合模式(Composite)
- Java设计模式菜鸟系列(十二)组合模式建模与实现
- 设计模式之十二:组合模式(composite)
- Java设计模式偷跑系列(十二)组合模式建模和实现
- 小菜编程成长记(十二 无熟人难办事?——聊设计模式迪米特法则)
- .NET实用设计模式:组合模式(Composite)
- 设计模式之Composite(组合)
- 设计模式 --- 组合模式(Composite) 精选经验合集
- 设计模式学习笔记(十二)——Flyweight享元模式
- 设计模式(8)-组合模式(Composite)
- .NET中的设计模式三:组合模式 选择自 lane_cn 的 Blog
- 设计模式学习笔记(十二)——Flyweight享元
- 设计模式之Composite(组合)
- 设计模式与泡mm的关系之Composite组合模式及组合模式的再思考
- java设计模式之Composite(组合) (转)
- 设计模式之Composite组合设计模式
- 窥视设计模式之组合模式(composite)