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?
Solution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PublisherSubscriber
{
class Program
{
static void Main(string[] args)
{
Publisher p = new Publisher();
Console.WriteLine("Message: ");
string s = Console.ReadLine();
p.Publish(s);
Console.Read();
}
}
class Publisher
{
public delegate void NotifyDelegate(string message);
public event NotifyDelegate NotifyMessageToSubscribers;
Print p ;
Fax f ;
Broadcast b ;
public Publisher()
{
p = new Print(this);
f = new Fax(this);
b = new Broadcast(this);
}
public void Publish(string message)
{
NotifyMessageToSubscribers(message);
}
}
class Print
{
Publisher _publisher;
public Print(Publisher p)
{
_publisher = p;
//Subscribe to publisher event
Subscribe();
}
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;
//Subscribe to publisher event
Subscribe();
}
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;
//Subscribe to publisher event
Subscribe();
}
public void Subscribe()
{
//Publisher.NotifyMessageToSubscribers += doBroadcast;
}
public void doBroadcast(string message)
{
Console.WriteLine("Broadcasting: " + message);
}
}
}