Monday, July 14, 2008

Observer Design Pattern


Observer pattern involves a one-many dependency between objects where a change in an object(subject) needs to be notified to all it's dependents(observers).

Example: Consider a scenario where a job posting at some company got multiple applications. Whenever the job status changes (filled, removed or suspended) all the applicants of the job should be notified. In this case job object is subject and all the applicants are observers.

As you can see below "Job" is the subject class and all applicants of that particular job are observers. Job class has "Add" and "Remove" methods for adding and removing applicants to it's list. Whenever job status changes all the applicant objects would be notified through Notify method which in turn calls the "Update" method of the applicant object.

public class Job

{
private ArrayList applicants;
private JobStatus statusOfJob;
public Job()
{
applicants = new ArrayList();
}
public void Add(Applicant candidate)
{
applicants.Add(candidate);
}
public void Remove(Applicant candidate)
{
applicants.Remove(candidate);
}
public void Notify()
{
foreach (Applicant candidate in applicants)
{

candidate.Update(this);

}
}
public JobStatus Status {
get
{
return statusOfJob;
}
set
{
statusOfJob = value;

Notify();

}

}

}

//Jobstatus enumerator

public enum JobStatus

{

FILLED,

SUSPENDED,

REMOVED

};

/// This is Observer.

public class Applicant

{

//declare variables
string fname;
string lname;
string emailID;
string phoneNo;
public Applicant()
{
//
// TODO: Add constructor logic here //
}

#region Properties for exposing the member variables

#endregion
public void Update(Job appliedJob)

{

switch(appliedJob.Status)

{

case JobStatus.FILLED:
//Do something like sending email, //updating database, etc
break;
case JobStatus.REMOVED:

//Do something like sending email, //updating database, etc
break;
case JobStatus.SUSPENDED:

//Do something like sending email, //updating database, etc
break;
}
//Your own functionality
//End Of Functionality
}
}

Best Regards

No comments: