Simple Observer Design pattern example in C#
The Reference URL is:
http://www.java2s.com/Code/CSharp/Design-Patterns/ObserverPatternDemo.htm
============================================================================
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleExample.Design_Pattren
{
public delegate void ChangedEventHandler(object sender,EventArgs e);
public class Subject
{
private string _data;
public event ChangedEventHandler Changed;
#region Default Constructor
public Subject()
{
}
#endregion
public string Data
{
get { return _data; }
set
{
_data = value;
this.OnChanged(EventArgs.Empty);
}
}
protected virtual void OnChanged(EventArgs e)
{
if (Changed != null)
this.Changed(this, e);
}
}
public class Observer
{
private Subject Subjectdata;
private string ObserverName;
public Subject ObservedObject
{
get { return Subjectdata; }
set { Subjectdata = value; }
}
private void DataChanged(object sender, EventArgs e)
{
Console.WriteLine("Notification "+ObserverName+" "+Subjectdata.Data);
}
public void Attach()
{
Subjectdata.Changed += new ChangedEventHandler(DataChanged);
}
public void Detach()
{
Subjectdata.Changed -= new ChangedEventHandler(DataChanged);
}
public Observer(string name)
{
this.ObserverName = name;
}
}
public class MainClass
{
public static void Main()
{
Subject sub = new Subject();
Observer observerA = new Observer("Observer A");
Observer observerB = new Observer("Observer B");
observerA.ObservedObject = sub;
observerB.ObservedObject = sub;
observerA.Attach();
observerB.Attach();
sub.Data = "1";
observerA.Detach();
//observerA.Detach();
sub.Data = "2";
sub.Data = "3";
Console.ReadKey();
}
}
}
===========================================================================
No comments:
Post a Comment