Monday, July 30, 2007

Observer pattern : broadcast the message

Hi,
Am back with a new post.
today we can focus on a new design pattern- "Observer pattern".

let us consider this scenario -
we have a candidate, who wants to get a job. The candidate informs a Job Consultant about this.

design -
we can design this in two ways
1) the candidate goes to the job consultant very often and then gets the status from him (this is nothing but polling)
2) the Job Consultant comes to know when there is a vacancy and then informs all the people for whom he is consulting. (this is broadcast)

disadvantage with option 1 is that some classes have to poll and polling takes a very long time.
even in the real life scenario, the candidates would not prefer to go to the consultant every "now and then" just to get the status neither would the consultant like being disturbed.
so both the candidate and the consultants would prefer option 2.

This is our observer pattern.
we have a an observer class (in our case "JobConsultant") which maintains a list of all the subjects which it is going to observe (here the subject is the "candidate").
All the subjects have to subscribe to the Observer;the subject can also unsubscribe; this is similar to a magazine subscription mechanism.

the observer will broadcast a message to all the subjects subscribed (just like our newspaper vendors).




using System;
using System.Collections.Generic;
using System.Text;

namespace ObserverPattern
{
public interface IJobConsultant
{

void Subscribe(Icandidate candidate);
void UnSubscribe(Icandidate candidate);
void OnVacancy();
}
public class JobConsultant : IJobConsultant
{
System.Collections.ArrayList Candidates;

public JobConsultant()
{
Candidates = new System.Collections.ArrayList();
}
public void UnSubscribe(Icandidate candidate)
{
Candidates.Remove(candidate);

}
public void Subscribe(Icandidate candidate)
{
Candidates.Add(candidate);
}

public void OnVacancy()
{
foreach (Icandidate Obj in Candidates)
{
Obj.notify();
}
}

}

public interface Icandidate
{
void notify();
void unSubscribe();
}

class candidate :Icandidate
{
string CandidateName;
IJobConsultant jobConsultant;
public candidate(string Name, IJobConsultant pjobConsultant)
{
CandidateName = Name;
jobConsultant = pjobConsultant;
jobConsultant.Subscribe((Icandidate)this);
}

public void unSubscribe()
{
jobConsultant.UnSubscribe(this);

}
public void notify()
{
Console.WriteLine("vacanacy created "+ CandidateName);
}
}
}


so now our classes and interfaces have been developed, we need to invoke this .
we can invoke this using the following the code:

IJobConsultant ObjJobConsultant = new JobConsultant();
candidate can1 = new candidate("candidate1", ObjJobConsultant);

ObjJobConsultant.OnVacancy();

what is the output?
the output will be

vacanacy created candidate1

No comments: