⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 class1.cs

📁 《深入浅出设计模式》的完整源代码
💻 CS
字号:
using System;
using System.Collections;
//项目类
class Item
{

	string name;
	public Item( string name )
	{
		this.name = name;
	}
	public string Name
	{
		get{ return name; }
	}
}
// Aggregate抽象聚合类
abstract class AbstractCollection
{
	abstract public Iterator CreateIterator();
}
// ConcreteAggregate具体聚合
class Collection : AbstractCollection
{
	private ArrayList items = new ArrayList();
	public override Iterator CreateIterator()
	{
		return new Iterator( this );
	}
	public int Count
	{
		get{ return items.Count; }
	}
	// 索引
	public object this[ int index ]
	{
		get{ return items[ index ]; }
		set{ items.Add( value ); }
	}
}
// 抽象迭代器Iterator
abstract class AbstractIterator
{
	abstract public Item First();
	abstract public Item Next();
	abstract public bool IsDone();
	abstract public Item CurrentItem();
}
// 具体迭代器ConcreteIterator
class Iterator : AbstractIterator
{
	private Collection collection;
	private int current = 0;
	private int step = 1;
	public Iterator( Collection collection )
	{
		this.collection = collection;
	}
	//步长
	public int Step
	{
		get{ return step; }
		set{ step = value; }
	}
	//最初
	override public Item First()
	{
		current = 0;
		return (Item)collection[ current ];
	}
	//下一个
	override public Item Next()
	{
		current += step;
		if( !IsDone() )
			return (Item)collection[ current ];
		else
			return null;
	}
	//现时项目
	override public Item CurrentItem()
	{
		return (Item)collection[ current ];
	}
	//是不是到了最后
	override public bool IsDone()
	{
		return current >= collection.Count ? true : false ;
	}
}

/// <summary>
/// 迭代器应用测试
/// </summary>
public class IteratorApp
{
	public static void Main(string[] args)
	{
		//建立聚集
		Collection collection = new Collection();
		collection[0] = new Item( "Item 0" );
		collection[1] = new Item( "Item 1" );
		collection[2] = new Item( "Item 2" );
		collection[3] = new Item( "Item 3" );
		collection[4] = new Item( "Item 4" );
		collection[5] = new Item( "Item 5" );
		collection[6] = new Item( "Item 6" );
		collection[7] = new Item( "Item 7" );
		collection[8] = new Item( "Item 8" );
		//生成迭代器
		Iterator iterator = new Iterator( collection );
 		//步长为2,跳跃一个项目。
		iterator.Step = 2;
		//用迭代器循环聚集
		for( Item item = iterator.First();
			!iterator.IsDone(); item = iterator.Next() )
		{
			Console.WriteLine( item.Name );
		}
		Console.Read();
	}
}  

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -