迭代器模式
题目
电视机遥控器就是一个迭代器的实例,通过它可以实现对电视机频道集合的遍历操作,现有TCL和创维两种品牌电视机,模拟电视机遥控器的实现。以下给出了一种实现方式的UML类图。
类图

【分析】
图中Television是抽象聚合类,具体聚合类SkyworthTelevision,其中方法createIterator()创建对应的具体SkyworthIterator对象,具体聚合类TCLTelevision,其中方法createIterator()创建对应的具体TCLIterator对象。TVIterator为抽象迭代器类,具体迭代器类SkyworthIterator和TCLIterator中定义了各自的访问遍历的方法。
界面

相关代码
//抽象聚合类
public interface Television {
TVIterator createIterator();
}
//具体聚合类
public class TCLTelevision implements Television{
public Object[] obj={"频道1","频道2","频道3","频道4","频道5"};
public TVIterator createIterator()
{
return new TCLIterator(this);
}
}
public class SkyworthTelevision implements Television{
public Object[] obj = {"CCTV-1", "CCTV-2", "CCTV-3", "CCTV-4"};
public TVIterator createIterator()
{
return new SkyworthIterator(this);
}
}
//抽象迭代器类
public interface TVIterator {
void setChannel(int i);
void next();
void previous();
boolean isLast();
Object currentChannel();
boolean isFirst();
}
//具体迭代器类
public class TCLIterator implements TVIterator{
private int currentIndex=0;
private TCLTelevision tcl;
public TCLIterator(TCLTelevision tcl) {
this.tcl=tcl;
}
public void next()
{
if(currentIndex<tcl.obj.length)
{
currentIndex++;
}
}
public void previous()
{
if(currentIndex>0)
{
currentIndex--;
}
}
public void setChannel(int i)
{
currentIndex=i;
}
public Object currentChannel()
{
return tcl.obj[currentIndex];
}
public boolean isLast()
{
return currentIndex==tcl.obj.length;
}
public boolean isFirst()
{
return currentIndex==0;
}
}
public class SkyworthIterator implements TVIterator{
private int currentIndex = 0;
private SkyworthTelevision skyworth;
public SkyworthIterator(SkyworthTelevision skyworth) {
this.skyworth=skyworth;
}
public void next() {
if (currentIndex < skyworth.obj.length) {
currentIndex++;
}
}
public void previous() {
if (currentIndex > 0) {
currentIndex--;
}
}
public void setChannel(int i) {
if (i >= 0 && i <= skyworth.obj.length) {
currentIndex = i;
}
}
public Object currentChannel() {
return skyworth.obj[currentIndex];
}
public boolean isFirst() {
return currentIndex == 0;
}
public boolean isLast() {
return currentIndex == skyworth.obj.length;
}
}
//客户端
public class Client {
public static void display(Television tv)
{
TVIterator i=tv.createIterator();
System.out.println("电视机频道:");
while(!i.isLast())
{
System.out.println(i.currentChannel().toString());
i.next();
}
}
public static void main(String[] args) {
Television tv = new TCLTelevision();
display(tv);
}
}
结果

本文通过电视遥控器为例,介绍了迭代器模式的应用。模拟TCL和创维电视机,利用迭代器实现对电视频道的遍历。文章包含UML类图分析,并提供了相关代码实现。
751

被折叠的 条评论
为什么被折叠?



