package com.example.designmodedemo.principle.iterator;
import java.util.List;
public class MyIterator implements Iterator{
private List
【抽象聚合角色】,代码如下:
package com.example.designmodedemo.principle.iterator;
public interface Aggregate {
public void add(Object object);// 新增元素
public void remove(Object object);// 移除元素
public Iterator getIterator();// 获取迭代器
}
【具体聚合角色】,代码如下:
package com.example.designmodedemo.principle.iterator;
import java.util.ArrayList;
import java.util.List;
public class MyAggregate implements Aggregate {
private List list = new ArrayList<>();
@Override
public void add(Object object) {
list.add(object);
}
@Override
public void remove(Object object) {
list.remove(object);
}
@Override
public Iterator getIterator() {
return (new MyIterator(list));
}
}
【客户端】,调用代码如下:
private void principle_aggregate() {
// 创建聚合对象,并添加元素
Aggregate myAggregate = new MyAggregate();
myAggregate.add("刺客信条 奥德赛");
myAggregate.add("荒野大镖客2");
myAggregate.add("巫师3");
System.out.println(":> 聚合对象中内容如下:");
// 获取迭代器对象,并遍历迭代器打印每一个元素内容
Iterator myIterator = myAggregate.getIterator();
while (myIterator.hasNext()){
Object obj = myIterator.next();
System.out.print(obj.toString() + "t");
}
// 使用迭代器获取第一个元素
Object firstObj = myIterator.first();
System.out.println("n:> First element is : " + firstObj.toString());
}
评论列表(0条)