迭代器与组合模式

迭代器模式

Definition: 提供一个接口顺序访问一个聚合对象的元素,而不暴露其内部实现细节
在C#中体现为IEnumerator接口的Current, MoveNext(), Reset()
迭代集合时,将不同的集合类封装起来,只对外暴露一个迭代器
 

组合模式

Definition: 允许将对象组合成树型结构来表现「整体 / 部分」层次结构
也就是说,一个聚合对象的元素可以是 元素(leaf)或者子聚合对象
notion image
 
public abstract class MenuComponent { // Operations public virtual void Operation() { throw new NotSupportedException(); } // Components related public virtual void Add(MenuComponent menuComponent) { throw new NotSupportedException(); } public virtual void Remove(MenuComponent menuComponent) { throw new NotSupportedException(); } public virtual MenuComponent GetChild(int index) { throw new NotSupportedException(); } } public class Menu : MenuComponent { public List<MenuComponent> MenuComponents; public override void Operation() { foreach (var com in MenuComponents) { com.Operation(); } } public override void Add(MenuComponent menuComponent) { MenuComponents.Add(menuComponent); } public override void Remove(MenuComponent menuComponent) { MenuComponents.Remove(menuComponent); } public override MenuComponent GetChild(int index) { return MenuComponents[index]; } } public class MenuItem : MenuComponent { private string name; private string description; public MenuItem(string name, string description) { this.name = name; this.description = description; } public override void Operation() { Console.WriteLine($"{name}: {description}") } }