- Publisher-Subscriber is a messaging pattern.
- Publisher is the sender of the message. (PUSH)
- Publisher does not have to know about the subscribers.
- Subscribers has the control to subscribe/unsubscribe message
Reference: http://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern
Scenario: There is a publisher and many subscribers (like Printer, Fax, Web server etc). Whenever Publisher gets file, it should notify the subscribers. And subscriber should have the authority to subscribe/not subscribe. How will you design this approach?
class Program
{
static void Main(string[] args)
{
//create publisher
Publisher p = new Publisher();
//Create subscribers
Print pr = new Print(p);
Fax f = new Fax(p);
Broadcast b = new Broadcast(p);
//subscribe
pr.Subscribe();
b.Subscribe();
//message
Console.WriteLine("Message: ");
string s = Console.ReadLine();
//push message to subscribers
p.Publish(s);
Console.Read();
}
}
class Publisher
{
public delegate void NotifyDelegate(string message);
public event NotifyDelegate NotifyMessageToSubscribers;
public void Publish(string message)
{
NotifyMessageToSubscribers(message);
}
}
class Print
{
Publisher _publisher;
public Print(Publisher p)
{
_publisher = p;
}
public void Subscribe()
{
_publisher.NotifyMessageToSubscribers += doPrint;
}
public void doPrint(string message)
{
Console.WriteLine("Printing: " + message);
}
}
class Fax
{
Publisher _publisher;
public Fax(Publisher p)
{
_publisher = p;
}
public void Subscribe()
{
_publisher.NotifyMessageToSubscribers += doFax;
}
public void doFax(string message)
{
Console.WriteLine("Faxing: " + message);
}
}
class Broadcast
{
Publisher _publisher;
public Broadcast(Publisher p)
{
_publisher = p;
}
public void Subscribe()
{
_publisher.NotifyMessageToSubscribers += doBroadcast;
}
public void doBroadcast(string message)
{
Console.WriteLine("Broadcasting: " + message);
}
}
No comments:
Post a Comment