关于观察者模式的原型

时间:2014-02-21 19:07:00

标签: design-patterns prototype

请帮我设计C#中观察者模式的原型。 什么是观察者模式? 怎样关于观察者模式的原型? 在C#.Net

1 个答案:

答案 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();
    }
 }
 }