设计模式----迭代器模式(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();}
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);}}
package com.designPattern.iterator;import java.util.Iterator;public interface IProjectIterator extends Iterator<IProject>{}
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() {}}
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