标签:
迭代器模式定义:它提供一种方法访问一个容器对象中各个元素,而又不暴露该对象的内部细节。
(迭代器是为容器服务的。能容纳对象的所有类型都可以称之为容器。例如:Collection集合类型、map类型。由于现在的集合都提供了迭代器所以这个模式现在应用之处很少)
迭代器有以下角色:
1、Iterator抽象迭代器。基本有三个方法:hasNext(),next(),remove()。
2、ConcreteIterator具体迭代器。
3、Aggregate抽象容器。
4、ConcreteAggregate具体容器。
类图如下:
实现代码如下:
抽象的迭代器:
package com.designpatterns.iterator; import java.util.Iterator; /** * @author WSYW126 * @version 2016年5月5日下午6:42:28 */ public interface IProjectIterator extends Iterator<Object> { }
package com.designpatterns.iterator; import java.util.ArrayList; /** * @author WSYW126 * @version 2016年5月5日下午6:43:37 */ public class ProjectIterator implements IProjectIterator { private ArrayList<IProject> rs = new ArrayList<>(); private int currentItem = 0; public ProjectIterator(ArrayList<IProject> rs) { this.rs = rs; } @Override public boolean hasNext() { boolean b = false; if (this.currentItem < this.rs.size()) { b = true; } return b; } @Override public IProject next() { return this.rs.get(currentItem++); } @Override public void remove() { } }
package com.designpatterns.iterator; /** * @author WSYW126 * @version 2016年5月5日下午6:45:09 */ public interface IProject { public void add(String name, int num, int cost); public String getProjectInfo(); public IProjectIterator iterator(); }
package com.designpatterns.iterator; import java.util.ArrayList; /** * @author WSYW126 * @version 2016年5月5日下午6:49:21 */ public class Project implements IProject { private ArrayList<IProject> rs = new ArrayList<>(); private String name = ""; private int num = 0; private int cost = 0; public Project() { } private Project(String name, int num, int cost) { this.name = name; this.num = num; this.cost = cost; } @Override public void add(String name, int num, int cost) { this.rs.add(new Project(name, num, cost)); } @Override public String getProjectInfo() { String inf = ""; inf = inf + "项目名称是:" + this.name; inf = inf + "\t项目的人数:" + this.num; inf = inf + "\t项目的费用:" + this.cost; return inf; } @Override public IProjectIterator iterator() { return new ProjectIterator(this.rs); } }
package com.designpatterns.iterator; /** * @author WSYW126 * @version 2016年5月6日下午6:06:13 */ public class Boss { public static void main(String[] args) { IProject project = new Project(); project.add("星际争霸", 10, 1000); project.add("超级英雄", 100, 100000); for (int i = 0; i < 10; i++) { project.add("第" + i + "个项目", i * 5, i * 10000); } IProjectIterator projectIterator = project.iterator(); while (projectIterator.hasNext()) { IProject p = (IProject) projectIterator.next(); System.out.println(p.getProjectInfo()); } } }
参考资料:
设计模式之禅
备注:
转载请注明出处
http://blog.csdn.net/wsyw126/article/details/51333750
by WSYW126
标签:
原文地址:http://blog.csdn.net/wsyw126/article/details/51333750