请帮我设计C#中观察者模式的原型。 什么是观察者模式? 怎样关于观察者模式的原型? 在C#.Net
答案 0 :(得分:1)
<强>观察强>
<强> IObserver.cs 强>
namespace ObserverOPC.Observer
{
public interface IObserver
{
void Notify(int t1,int t2);
}
}
<强> Observer1.xaml.cs 强>
using ObserverOPC.Subject;
namespace ObserverOPC.Observer
{
public partial class Observer1 : Window,IObserver
{
public Observer1()
{
InitializeComponent();
}
public void Notify(int _t1, int _t2)
{
//get value here
}
}
}
<强>主题强>
<强> ISubject.cs 强>
namespace ObserverOPC.Subject
{
public interface ISubject
{
void Subscribe(Observer.IObserver objObserver );
void UnSubscribe(Observer.IObserver objObserver);
void NotifySubscribers();
}
}
<强> OPCAPI.cs 强>
namespace ObserverOPC.Subject
{
public interface OPCAPI
{
void Update();
}
}
<强> OPCClient.cs 强>
using ObserverOPC.Observer;
using OPCAutomation;
namespace ObserverOPC.Subject
{
public class OPCClient:OPCAPI,ISubject
{
private IList<Observer.IObserver> _observers=new List<IObserver>();
public void Update()
{
}
public void Subscribe(IObserver observer)
{
_observers.Add(observer);
}
public void UnSubscribe(IObserver observer)
{
_observers.Remove(observer);
}
public void NotifySubscribers()
{
foreach (IObserver s in _observers)
{
s.Notify(_tag1Value,_tag2Value);
}
}
}
}
<强> MainWindow.xaml.cs 强>
using ObserverOPC.Observer;
using ObserverOPC.Subject;
namespace ObserverOPC
{
public partial class MainWindow : Window
{
OPCClient objOpcClient= new OPCClient();
public MainWindow()
{
IObserver _client1Observer=new Observer1();
IObserver _client2Observer = new Observer2();
//Register the Observers
objOpcClient.Subscribe(_client1Observer);
objOpcClient.Subscribe(_client2Observer);
objOpcClient.Update();
this.Hide();
}
}
}