Observer pattern is used, when there are multiple listeners to a subject.
It can also be called as listener design pattern.
Instead of observers calling the subject every time to check if any update in subject(polling),Subject will notify all the listeners(observers).
All the listeners or observers will be notified, if there is a change in subject's state.
Examples:
1.All kinds of notifications(like news,quotes etc..)
How to write Observer pattern code:
1.Write an Observable interface for subject
It can also be called as listener design pattern.
Instead of observers calling the subject every time to check if any update in subject(polling),Subject will notify all the listeners(observers).
All the listeners or observers will be notified, if there is a change in subject's state.
Examples:
1.All kinds of notifications(like news,quotes etc..)
How to write Observer pattern code:
1.Write an Observable interface for subject
public interface Observable { public void update(); }2.Define Subject class which implements Observable
import java.util.ArrayList; import java.util.List; public class Subject implements Observable{ List<Listeners> observers = new ArrayList<Listeners>(); public void subscribe(Listeners obs){ observers.add(obs); } public void update() { for(Listeners obj:observers){ obj.update(); } } }3.Define an interface for Listener classes
public interface Listeners { public void update(); }4.Define Listeners which implement Listener interface
First Listener:
public class FirstListener implements Listeners{ public void update(){ System.out.println("updating first Listener"); } }
Second Listener:
5.Main method to test the pattern.public class SecondListener implements Listeners{ public void update(){ System.out.println("updating second listener"); } }
public class Main { public static void main(String args[]) { Subject subject = new Subject(); subject.subscribe(new FirstListener()); subject.subscribe(new SecondListener()); subject.update(); } }
when subject gets updated,it will invoke update methods of
all the listeners subscribed to it.
Output will be like
updating first Listener
updating second listener