Java语言设计模式之组合模式(Composite)
2017-08-30 14:01
591 查看
实现 composite 模式的最简单的实例:
CompositeStructure .java
这是实现 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 模式的最简单的方法。当然这种方法在用于大型系统的时候可能会出现问题。但是,最好的做法可能就是从最简单的方法入手,而只在需要的时候才去改变它。
相关文章推荐
- Java设计模式透析之 —— 组合(Composite)
- java设计模式之组合模式(Composite)
- java23种设计模式--组合模式(composite)
- Java设计模式透析之 —— 组合(Composite)
- Java开发中的23种设计模式之十一:组合模式(Composite)
- Java设计模式透析之 —— 组合(Composite)
- JAVA设计模式十七--Composite(组合模式)
- Java设计模式透析之 —— 组合(Composite)
- Java经典设计模式-结构型模式-组合模式(Composite)
- java设计模式(十)——组合模式(Composite)
- Java设计模式透析之 —— 组合(Composite)
- Java设计模式 —— 组合(Composite)
- Java设计模式透析之 —— 组合(Composite)
- java设计模式之组合模式Composite
- JAVA设计模式十七:--Composite(组合模式)
- Java设计模式之结构型模式-组合模式(Composite)
- Java设计模式之组合模式(Composite)
- java 设计模式之: 组合模式(Composite)---1 【转】
- Java设计模式透析之 —— 组合(Composite)
- Java设计模式-组合模式(Composite)