java迭代器实现树的迭代

实现原理图:

在这里插入图片描述
正在学习Java语言迭代器,练习使用迭代器并自定义MyIterator接口达到以上逻辑。
主要思路:把组件分成两种CompositeComponent(复合组件)和AtomicComponent(原组件),它们继承自同一个抽象类(Component,复合组件有子代,子代再继续分两种。

接口

public interface MyIterator {
    boolean hasNext();
 	Component next();
}

抽象类

abstract public class Component {
    protected int id;
    protected String name;
    protected double price;

    public Component(){
    }

    public Component(int id, String name,double price){
        this.id = id;
        this.name = name;
        this.price = price;
    }

    public int getId(){
        return id;
    }

    public void setId(int id){
        this.id=id;
    }

    public String getName(){
        return name;
    }

    public void setName(String name){
        this.name = name;
    }

    public double getPrice(){
        return price;
    }

    public void setPrice(double price){
        this.price = price;
    }

    public abstract void add(Component component) throws UnsupportedOperationException;

    public abstract void remove(Component component) throws UnsupportedOperationException;

    public abstract double calcPrice();

    public abstract MyIterator iterator();

    @Override
    public boolean equals(Object ncp){
        Component component = (Component)ncp;
        if(!super.equals(component))
            return false;
        if(this.id==component.id)
            return true;
        else
            return false;
    }

    @Override
    public String toString(){
        return "id:"+id+", name:"+name+", price"+price;
    }
}

复合组件

public class CompositeComponent extends Component {
    protected ComponentList childs = new ComponentList();

    public CompositeComponent() {

    }

    public CompositeComponent(int id, String name, double price) {
        this.setId(id);
        this.setName(name);
        this.setPrice(price);
    }

    public ComponentList getChildren(){
        return this.childs;
    }

    @Override
    public void add(Component component) throws UnsupportedOperationException {
        childs.add(component);
        calcPrice();
    }

    @Override
    public void remove(Component component) throws UnsupportedOperationException {
        childs.remove(component);
    }

    @Override
    public double calcPrice() {
        double price = 0.0;
        for(Component child:childs){
            price += child.getPrice();
        }
        this.setPrice(price);
        return this.getPrice();
    }

    @Override
    public MyIterator iterator() {
        MyIterator chit = new CompositeIterator(this);
        return chit;
    }

    @Override
    public String toString(){
        StringBuffer components = new StringBuffer();

        components.append("\n"+super.toString());

        for(Component child:childs){
            components.append("\n"+child.toString());
        }
        return components.toString();
    }
}

###原组件

public class AtomicComponent extends Component {
    public AtomicComponent(){

    }
    public AtomicComponent(int id,String name, double price){
        this.setId(id);
        this.setName(name);
        this.setPrice(price);
        toString();
    }

    @Override
    public void add(Component component) throws UnsupportedOperationException {        
    }

    @Override
    public void remove(Component component) throws UnsupportedOperationException {
    }

    @Override
    public double calcPrice() {
        return this.price;
    }

    @Override
    public MyIterator iterator() {
        MyIterator nit =new NullIterator();
        return nit;
    }

    @Override
    public String toString(){
        return super.toString();
    } 
}

复合组件迭代器


public class CompositeIterator implements MyIterator {

    protected ComponentList list =  new ComponentList();
    public CompositeIterator(Component c){
        list.add(c);
    }

    @Override
    public boolean hasNext() {
        if(0== list.size()||list.isEmpty())
            return false;
        else
            return true;
    }

    @Override
    public Component next() {
        if(hasNext()){
            Component c = list.get(0);
            System.out.println("id: "+c.getId()+", name:"+c.getName()+", price:"+c.getPrice());
            if(list.get(0) instanceof CompositeComponent){
                list.addAll( (((CompositeComponent) list.get(0)).getChildren()));
                System.out.println("\nsub-components of "+list.get(0).name+":\n");
            }
            list.remove(0);
            return c;
        }
        else
            return null;
    }   
}

原组件迭代器

public class NullIterator implements MyIterator{

    @Override
    public boolean hasNext() {
        return false;
    }

    @Override
    public Component next() {
        return null;
    }
    
}

最后调用

public class Test {
    public static void main(String[] args) {
        int id = 0;
        //计算对象
        Component computer = new CompositeComponent(id++, "Think Pad",0.0);
        //键盘对象
        Component keyboard = new AtomicComponent(id++, "Keyboard",20.0);
        //鼠标对象
        Component mouse = new AtomicComponent(id++, "Mouse",20.0);
        //显示器对象
        Component monitor = new AtomicComponent(id++,"Monitor",1000.0)
        //主机对象
        Component mainFrame = new CompositeComponent(id++, "Main frame",0.0);
        //硬盘对象
        Component hardDisk = new AtomicComponent(id++, "Hard disk",1000.0);
        //电源对象
        Component powerSupplier = new AtomicComponent(id++, "Power supplier",500.0);
        //主板对象
        Component mainBoard = new CompositeComponent(id++, "Main board",0.0);
        //CPU对象
        Component cpu = new AtomicComponent(id++, "CPU",1500.0);
        //显卡对象
        Component videoCard = new AtomicComponent(id++, "Video card",900.0);
        //网卡对象
        Component networkCard = new AtomicComponent(id++, "Network card",100.0);
        mainBoard.add(cpu);
        mainBoard.add(videoCard);
        mainBoard.add(networkCard);
        mainFrame.add(hardDisk);
        mainFrame.add(powerSupplier);       
        mainFrame.add(mainBoard);        
        computer.add(keyboard);
        computer.add(mouse);
        computer.add(monitor);
        computer.add(mainFrame);

        MyIterator it = computer.iterator();
        while(it.hasNext()){
            Component c = it.next();
        }
    }
}        

新人上路,有更好的方法欢迎讨论。

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
无限级Java递归) 2007-02-08 10:26 这几天,用java写了一个无限极的,递归写的,可能代码不够简洁,性能不够好,不过也算是练习,这几天再不断改进。前面几个小图标的判断,搞死我了。 package com.nickol.servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.nickol.utility.DB; public class category extends HttpServlet { /** * The doGet method of the servlet. * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out .println(""); out.println(""); out.println(" Category" + "" + "body{font-size:12px;}" + "" + "" + ""); out.println(" "); out.println(showCategory(0,0,new ArrayList(),"0")); out.println(" "); out.println(""); out.flush(); out.close(); } public String showCategory(int i,int n,ArrayList frontIcon,String countCurrent){ int countChild = 0; n++; String webContent = new String(); ArrayList temp = new ArrayList(); try{ Connection conn = DB.GetConn(); PreparedStatement ps = DB.GetPs("select * from category where pid = ?", conn); ps.setInt(1, i); ResultSet rs = DB.GetRs(ps); if(n==1){ if(rs.next()){ webContent += "";//插入结尾的减号 temp.add(new Integer(0)); } webContent += " ";//插入站点图标 webContent += rs.getString("cname"); webContent += "\n"; webContent += showCategory(Integer.parseInt(rs.getString("cid")),n,temp,"0"); } if(n==2){ webContent += "\n"; }else{ webContent += "\n"; } while(rs.next()){ for(int k=0;k<frontIcon.size();k++){ int iconStatic = ((Integer)frontIcon.get(k)).intValue(); if(iconStatic == 0){ webContent += "";//插入空白 }else if(iconStatic == 1){ webContent += "";//插入竖线 } } if(rs.isLast()){ if(checkChild(Integer.parseInt(rs.getString("cid")))){ webContent += "";//插入结尾的减号 temp = (ArrayList)frontIcon.clone(); temp.add(new Integer(0)); }else{ webContent += "";//插入结尾的直角 } }else{ if(checkChild(Integer.parseInt(rs.getString("cid")))){ webContent += "";//插入未结尾的减号 temp = (ArrayList)frontIcon.clone(); temp.add(new Integer(1)); }else{ webContent += "";//插入三叉线 } } if(checkChild(Integer.parseInt(rs.getString("cid")))){ webContent += " ";//插入文件夹图标 }else{ webContent += " ";//插入文件图标 } webContent += rs.getString("cname"); webContent += "\n"; webContent += showCategory(Integer.parseInt(rs.getString("cid")),n,temp,countCurrent+countChild); countChild++; } webContent += "\n"; DB.CloseRs(rs); DB.ClosePs(ps); DB.CloseConn(conn); }catch(Exception e){ e.printStackTrace(); } return webContent; } public boolean checkChild(int i){ boolean child = false; try{ Connection conn = DB.GetConn(); PreparedStatement ps = DB.GetPs("select * from category where pid = ?", conn); ps.setInt(1, i); ResultSet rs = DB.GetRs(ps); if(rs.next()){ child = true; } DB.CloseRs(rs); DB.ClosePs(ps); DB.CloseConn(conn); }catch(Exception e){ e.printStackTrace(); } return child; } } --------------------------------------------------------------------- tree.js文件 function changeState(countCurrent,countChild){ var object = document.getElementById("level" + countCurrent + countChild); if(object.style.display=='none'){ object.style.display='block'; }else{ object.style.display='none'; } var cursor = document.getElementById("cursor" + countCurrent + countChild); if(cursor.src.indexOf("images/tree_minus.gif")>=0) {cursor.src="images/tree_plus.gif";} else if(cursor.src.indexOf("images/tree_minusbottom.gif")>=0) {cursor.src="images/tree_plusbottom.gif";} else if(cursor.src.indexOf("images/tree_plus.gif")>=0) {cursor.src="images/tree_minus.gif";} else {cursor.src="images/tree_minusbottom.gif";} var folder = document.getElementById("folder" + countCurrent + countChild); if(folder.src.indexOf("images/icon_folder_channel_normal.gif")>=0){ folder.src = "images/icon_folder_channel_open.gif"; }else{ folder.src = "images/icon_folder_channel_normal.gif"; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值