using System;
using System.Collections;
using System.Collections.Generic;
namespace Observer
{
public interface IObserver
{
void Update(Object obj);
}
public interface IObservable
{
void Register(IObserver anObserver);
void UnRegister(IObserver anObserver);
void NotifyObservers(Object obj);
}
public class People : IObservable
{
private string m_name;
public string Name
{
get
{
return m_name;
}
set
{
m_name = value;
}
}
private int m_age;
public int Age
{
get
{
return m_age;
}
set
{
m_age = value;
NotifyObservers(m_age);
}
}
public void Print()
{
Console.WriteLine("Name:" + m_name + " Age:" + m_age);
}
#region Observer
private Hashtable m_observers;
public People()
{
m_observers = new Hashtable();
}
public void Register(IObserver anObserver)
{
m_observers.Add(anObserver,anObserver);
}
public void UnRegister(IObserver anObserver)
{
m_observers.Remove(anObserver);
}
public void NotifyObservers(Object obj)
{
foreach (IObserver observer in m_observers.Values)
{
observer.Update(obj);
}
}
#endregion
}
public class UI : IObserver
{
public void Update(Object obj)
{
Console.WriteLine("年龄:" + obj);
if(obj.GetType() == typeof(int))
{
Console.WriteLine("年龄:" + obj);
}
}
}
public class MainClass
{
public static void Main()
{
Console.WriteLine("Hello World");
People people = new People();
people.Name = "Lily";
people.Age = 18;
people.Print();
UI ui = new UI();
people.Register(ui);
people.Print();
people.Age = 20;
people.Print();
people.UnRegister(ui);
people.Age = 22;
people.Print();
}
}
}
观察者模式
最新推荐文章于 2024-09-01 15:47:48 发布