ObserverPattern

Type of the pattern:

The Observer Pattern is a behavioral design patterns (design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.)

 

Problem it solves:

Observer pattern also called publisher+subscriber model defines one to many dependency between objects so that when one object changes state all of its dependents are notified and updated automatically.

Subscriber, also called observer, is interested in publisher’s/subject’s state change so it registers with subject/publisher so that whenever subject’s state changes it is notified.

Examples:

Job aspirants who are registered with a job consultant are observers. Job consultant is a subject which notifies all aspirants once job is available in the market. Here if an aspirant keeps on calling job consultant it will be waste of time & resources for both consultant and aspirant. Better approach is that consultant calls all the interested candidates once job is available

Below class diagram depicts this concept:

ObserverPattern

 

 

 

 

 

 

 

Code for JobConsultant will be as below:

 

public class JobConsultant implements IJobConsultant{

 

private List<ICandidate>candidates = new ArrayList<ICandidate>();

private String jobDescription;

 

@Override

public void removeCandidate(ICandidate candidate) {

candidates.remove(candidate);

 

}

 

@Override

public void registerCandidate(ICandidate candidate) {

candidates.add(candidate);

 

}

 

@Override

public void notifyCandidates() {

for(ICandidate candidate : candidates){

candidate.update(this.jobDescription);

}

 

}

 

public void setJobDescription(String message){

this.jobDescription = message;

notifyCandidates();

}

 

 

 

}

 

Code for Candidate will be as below:

 

package com.techlabs.observer;

 

public class Candidate implements ICandidate {

 

private IJobConsultant jobConsultant;

 

public Candidate(IJobConsultant jobConsultant) {

this.jobConsultant = jobConsultant;

jobConsultant.registerCandidate(this);

}

 

@Override

public void update(String message) {

// TODO Auto-generated method stub

 

}

 

public void unsubscribeFromJobNotification() {

jobConsultant.removeCandidate(this);

}

 

}

 

Observer Pattern

Post navigation


Leave a Reply

Your email address will not be published. Required fields are marked *