之所以把这两个模式放在一起说是因为C#语句的关系。这两种模式实现起来变得很轻松或者说不一样了。
Observer(观察者)
运行结果
Iterator(迭代器)
分别实现IEnumerable和IEnumerator接口的类
C#泛型的支持使得iterator的实现更好些。
结果
Observer(观察者)
class Observer
{
public delegate void EventHandler(string state);
public event EventHandler changeEvent;
public void ChangeState(string state)
{
if (changeEvent != null)
{
changeEvent(state);
}
}
}
调用{
public delegate void EventHandler(string state);
public event EventHandler changeEvent;
public void ChangeState(string state)
{
if (changeEvent != null)
{
changeEvent(state);
}
}
}
static void Main(string[] args)
{
Observer obs = new Observer();
obs.changeEvent += new Observer.EventHandler(obs_changeEvent);
obs.ChangeState("Change");
Console.Read();
}
static void obs_changeEvent(string state)
{
Console.WriteLine("I see:" + state);
}
{
Observer obs = new Observer();
obs.changeEvent += new Observer.EventHandler(obs_changeEvent);
obs.ChangeState("Change");
Console.Read();
}
static void obs_changeEvent(string state)
{
Console.WriteLine("I see:" + state);
}
运行结果
Iterator(迭代器)
分别实现IEnumerable和IEnumerator接口的类
public class Tokens : IEnumerable
{
public string[] elements;
public Tokens(string source, char[] delimiters)
{
elements = source.Split(delimiters);
}
public IEnumerator GetEnumerator()
{
return new TokenEnumerator(this);
}
}
{
public string[] elements;
public Tokens(string source, char[] delimiters)
{
elements = source.Split(delimiters);
}
public IEnumerator GetEnumerator()
{
return new TokenEnumerator(this);
}
}
public class TokenEnumerator : IEnumerator
{
private int position = -1;
private Tokens t;
public TokenEnumerator(Tokens t)
{
this.t = t;
}
public bool MoveNext()
{
if (position < t.elements.Length - 1)
{
position++;
return true;
}
else
{
return false;
}
}
public void Reset()
{
position = -1;
}
public object Current
{
get
{
return t.elements[position];
}
}
}
调用{
private int position = -1;
private Tokens t;
public TokenEnumerator(Tokens t)
{
this.t = t;
}
public bool MoveNext()
{
if (position < t.elements.Length - 1)
{
position++;
return true;
}
else
{
return false;
}
}
public void Reset()
{
position = -1;
}
public object Current
{
get
{
return t.elements[position];
}
}
}
static void Main(string[] args)
{
Tokens tokens = new Tokens("a,b,c", new char[] { ',' });
IEnumerator iterator = tokens.GetEnumerator();
while (iterator.MoveNext())
{
string token = iterator.Current as string;
if (token != null)
{
Console.WriteLine(token);
}
}
Console.Read();
}
{
Tokens tokens = new Tokens("a,b,c", new char[] { ',' });
IEnumerator iterator = tokens.GetEnumerator();
while (iterator.MoveNext())
{
string token = iterator.Current as string;
if (token != null)
{
Console.WriteLine(token);
}
}
Console.Read();
}
C#泛型的支持使得iterator的实现更好些。
结果