迭代器模式,先占位,由于文章太耗时,后面补上。
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace SimpleFactory
{
class Program
{
static void Main(string[] args)
{
炸好的油条 youtiaos = new 炸好的油条();
youtiaos.添加一根油条(new 油条(50.3));
youtiaos.添加一根油条(new 油条(60.5));
youtiaos.添加一根油条(new 油条(52.4));
youtiaos.添加一根油条(new 油条(57.7));
Console.WriteLine($"一共炸好了几根油条:{youtiaos.Count}");
Console.WriteLine($"现在有个客人要买一根油条");
var iterator = youtiaos.GetEnumerator() as 油条遍历器;
if (iterator.MoveNext())
{
油条 youtiao = iterator.Current as 油条;
Console.WriteLine($"从炸好的油条中,取了一根给他。费用是{youtiao.价格}元,克重是{youtiao.克重}克");
iterator.RemoveCurrent();
}
iterator.Reset();
Console.WriteLine();
Console.WriteLine($"我们看下还剩下多少油条没卖掉,一共还有{youtiaos.Count}根油条没有卖掉");
while (iterator.MoveNext())
{
油条 youtiao = iterator.Current as 油条;
Console.WriteLine($"没卖掉的油条情况:克重是{youtiao.克重}");
}
}
}
public class 油条
{
private double _weight;
public 油条(double weight)
{
this._weight = weight;
}
public double 克重
{
get
{
return this._weight;
}
}
public decimal 价格
{
get
{
return 2.0M;
}
}
}
public class 炸好的油条 : IEnumerable
{
private List<油条> _youtiaos = new List<油条>();
public virtual int Count
{
get
{
return this._youtiaos.Count;
}
}
public void 添加一根油条(油条 youtiao)
{
this._youtiaos.Add(youtiao);
}
public IEnumerator GetEnumerator()
{
return new 油条遍历器(this._youtiaos);
}
}
public class 油条遍历器 : IEnumerator
{
private List<油条> _youtiaos;
private int _position;
internal 油条遍历器(List<油条> youtiaos)
{
this._youtiaos = youtiaos;
}
public object Current
{
get
{
return this._youtiaos[_position];
}
}
public bool MoveNext()
{
if (this._position < this._youtiaos.Count - 1)
{
this._position++;
return true;
}
else
{
return false;
}
}
public void RemoveCurrent()
{
this._youtiaos.Remove(this.Current as 油条);
}
public void Reset()
{
this._position = -1;
}
}
}