首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件开发 >

设计形式-迭代器模式(Iterator)

2013-08-01 
设计模式----迭代器模式(Iterator)IProject.java代码如下:package com.designPattern.iteratorpublic int

设计模式----迭代器模式(Iterator)
IProject.java代码如下:

package com.designPattern.iterator;public interface IProject {public void add(String name,int num,int cost);public String getProjectInfo();public IProjectIterator iterator();}



Project.java代码如下:

package com.designPattern.iterator;import java.util.ArrayList;public class Project  implements IProject{private ArrayList<IProject> projectList = new ArrayList<IProject>();private String name = "";private int num = 0;private int cost = 0;public Project(){}public Project(String name,int num,int cost){this.name = name;this.num = num;this.cost = cost;}@Overridepublic void add(String name, int num, int cost) {this.projectList.add(new Project(name,num,cost));}@Overridepublic String getProjectInfo() {String info = "项目名称是:"+this.name+"\t项目人数为:"+this.num+"\t项目费用为:"+this.cost;return info;}@Overridepublic IProjectIterator iterator() {return new ProjectIterator(this.projectList);}}


IProjectIterator.java代码如下:
package com.designPattern.iterator;import java.util.Iterator;public interface IProjectIterator extends Iterator<IProject>{}


ProjectIterator.java代码如下:
package com.designPattern.iterator;import java.util.ArrayList;public class ProjectIterator implements IProjectIterator{private ArrayList<IProject> projectList = new ArrayList<IProject>();private int currentItem = 0;public ProjectIterator(ArrayList<IProject> projectList){this.projectList = projectList;}@Overridepublic boolean hasNext() {boolean bool = true;if(this.currentItem>=projectList.size()||this.projectList.get(this.currentItem)==null){bool = false ;}return bool;}@Overridepublic IProject next() {return (IProject)this.projectList.get(this.currentItem++);}@Overridepublic void remove() {}}


Boss.java代码如下:
package com.designPattern.iterator;/** * JDK1.2之后出现的Iterator * @author yangjianzhou * */public class Boss {public static void main(String[] args) {IProject project = new Project();project.add("星球大战", 10, 100000);project.add("CS", 10, 100000);project.add("WOW", 10, 100000);project.add("地下城勇士", 10, 100000);for(int i=4;i<100;i++){project.add("第个"+i+"项目", 20, 100000);}IProjectIterator projectIterator = project.iterator();while(projectIterator.hasNext()){IProject p = projectIterator.next();System.out.println(p.getProjectInfo());}}}


运行结果如下:
项目名称是:星球大战项目人数为:10项目费用为:100000项目名称是:CS项目人数为:10项目费用为:100000项目名称是:WOW项目人数为:10项目费用为:100000项目名称是:地下城勇士项目人数为:10项目费用为:100000项目名称是:第个4项目项目人数为:20项目费用为:100000项目名称是:第个5项目项目人数为:20项目费用为:100000项目名称是:第个6项目项目人数为:20项目费用为:100000项目名称是:第个7项目项目人数为:20项目费用为:100000项目名称是:第个8项目项目人数为:20项目费用为:100000项目名称是:第个9项目项目人数为:20项目费用为:100000

热点排行