C# – Publish Subscribe Pattern

Posted: January 3, 2011 in C#, Design Patterns
Tags: , ,

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace DesignPatterns.PubSub
{
[TestClass]
public class TestSample
{
[TestMethod]
public void Main()
{
Publisher publisherService = new Publisher();
Subscriber1 sub1 = new Subscriber1(publisherService);
Subscriber2 sub2 = new Subscriber2(publisherService);

publisherService.Publish(“Published”);
}
}

public class Publisher
{
public delegate void PublishDelegate(object sender, InfoArgs args);
public event PublishDelegate PublishEvent;

public void OnPublishEvent(object sender, InfoArgs args)
{
if (PublishEvent != null)
PublishEvent(sender, args);
}

public void Publish(string info)
{
OnPublishEvent(this, new InfoArgs(info));
}
}

public class InfoArgs : EventArgs
{
private readonly string info;

public InfoArgs(string info)
{
this.info = info;
}

public string Info
{
get { return info; }
}
}

public class Subscriber1
{
private Publisher publisher;
public Subscriber1(Publisher pPublisher)
{
this.publisher = pPublisher;
pPublisher.PublishEvent += Action;
}

static void Action(object sender, InfoArgs args)
{
Console.WriteLine(“Subscriber1 Action: ” + args.Info);
}
}

public class Subscriber2
{
private Publisher publisher;
public Subscriber2(Publisher pPublisher)
{
this.publisher = pPublisher;
pPublisher.PublishEvent += Action;
}

static void Action(object sender, InfoArgs args)
{
Console.WriteLine(“Subscriber2 Action: ” + args.Info);
}
}
}

Reference –

http://www.akadia.com/services/dotnet_delegates_and_events.html

http://www.dotnetarchitecthouston.com/post/The-Publish-Subscribe-Pattern-in-C-and-some-gotchas.aspx

http://msdn.microsoft.com/en-us/library/ms752254.aspx – WCF

http://msdn.microsoft.com/en-us/library/ff649664.aspx – MS Patterens & Practices

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s