C# 设计模式(17)迭代器模式
迭代器模式
1. Yield Return
2. 提供统一的访问方式
代码实现:
食品类:
public class Food { public int Id { get; set; } public string Name { get; set; } public int Price { get; set; } }
菜单类:
public class KFCMenu { private readonly Food[] _foodArray = new Food[3]; public KFCMenu() { _foodArray[0]= new Food() { Id =01, Name = "hamburger", Price = 15 }; _foodArray[1] = new Food() { Id = 02, Name = "fries", Price = 5 }; _foodArray[2] = new Food() { Id = 03, Name = "Cola", Price = 10 }; } public Food[] GetFoods() { return _foodArray; } } public class MacDonaldMenu { private readonly List<Food> _foodArray = new List<Food>(); public MacDonaldMenu() { _foodArray.Add(new Food() { Id = 01, Name = "ketchup", Price = 10 }); _foodArray.Add(new Food() { Id = 01, Name = "big Mac", Price = 20 }); _foodArray.Add(new Food() { Id = 01, Name = "Apple Pie", Price = 15 }); } public List<Food> GetFoods() { return _foodArray; } }
自定义迭代器:
namespace IteratorPattern.Iterator { public interface IIterator { bool MoveNext(); object Current { get; } void Reset(); } public class KFCIterator:IIterator { private readonly KFCMenu _kfcMenu; public KFCIterator(KFCMenu kfcMenu) { _kfcMenu = kfcMenu; } private int _index = -1; public bool MoveNext() { return _kfcMenu.GetFoods().Length > (++_index); } public object Current => _kfcMenu.GetFoods()[_index]; public void Reset() { _index = -1; } } public class MacDonaldIterator:IIterator { private readonly MacDonaldMenu _macDonaldMenu; public MacDonaldIterator(MacDonaldMenu macDonaldMenu) { _macDonaldMenu = macDonaldMenu; } private int _index = -1; public bool MoveNext() { return _macDonaldMenu.GetFoods().Count > (++_index); } public object Current => _macDonaldMenu.GetFoods()[_index]; public void Reset() { _index = -1; } } }
代码调用:
class Program { static void Main(string[] args) { KFCMenu kfcMenu = new KFCMenu(); //.NET Iterator Food[] kfcFoods = kfcMenu.GetFoods(); foreach (var kfcFood in kfcFoods) { Console.WriteLine($"KFC Menu include {kfcFood.Name},price is {kfcFood.Price} RMB."); } //Custom Iterator KFCIterator kfcIterator = new KFCIterator(kfcMenu); while (kfcIterator.MoveNext()) { Console.WriteLine( $"Custom Iterator KFC Menu include {((Food) kfcIterator.Current).Name},price is {((Food) kfcIterator.Current).Price} RMB."); } MacDonaldMenu macDonaldMenu = new MacDonaldMenu(); //.NET Iterator List<Food> macDonaldFoods = macDonaldMenu.GetFoods(); foreach (var macDonaldFood in macDonaldFoods) { Console.WriteLine($"MacDonald Menu include {macDonaldFood.Name},price is {macDonaldFood.Price} RMB."); } //Custom Iterator MacDonaldIterator macDonaldIterator = new MacDonaldIterator(macDonaldMenu); while (macDonaldIterator.MoveNext()) { Console.WriteLine( $"Custom Iterator MacDonald Menu include {((Food) macDonaldIterator.Current).Name},price is {((Food) macDonaldIterator.Current).Price} RMB."); } } }
结果: