c# Observers模式 示例

用于显示数据的接口定义:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Observers
{
interface IDisplay
{
void Display();
}
}
天气数据类接口定义
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Observers { interface IWatherData { void AddObserver(IObservers o); void DelObserver(IObservers o); void SetWatherData(int Temperature, int Humidity); } }
 
观察者接口定义:
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Observers
{
interface IObservers
{
void update(int Temperature, int Humidity);
}
}

天气数据类的实现:

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace Observers
{
class WatherData:IWatherData
{
private int Temperature = 0;
private int Humidity = 0;
private ArrayList observers;
public WatherData()
{
observers = new ArrayList();
}

public void AddObserver(IObservers o)
{
observers.Add(o);
}

public void DelObserver(IObservers o)
{
if (observers.IndexOf(o) > 0)
{
observers.RemoveAt(observers.IndexOf(o));
}
}

public void SetWatherData(int intTemperature, int intHumidity)
{
Temperature = intTemperature;
Humidity = intHumidity;
WatherDataChanged();
}

public void WatherDataChanged()
{
for (int i = 0; i < observers.Count; i++)
{
((IObservers)observers[i]).update(Temperature, Humidity);
}
}
}
}

观察者类的实现:

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Observers
{
class Observer1:IObservers,IDisplay
{
private int intTemperature;
private int intHumidity;
public void update(int Temperature, int Humidity)
{
intTemperature = Temperature;
intHumidity = Humidity;
Display();
}

public void Display()
{
Console.WriteLine("Observer1:Temperature=" + intTemperature + ",Humidity=" + intHumidity);
}
}
}

主方法调用:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Observers
{
class Program
{
static void Main(string[] args)
{
IWatherData watherdata = new WatherData();
IObservers observer1 = new Observer1();
watherdata.AddObserver(observer1);
watherdata.SetWatherData(100,200);
watherdata.SetWatherData(200, 100);
Console.ReadKey();
}
}
}

 

 


 

你可能感兴趣的:(observer)