Observer Pattern
The observer pattern defines a one to many relation between objects so that when one object changes state, all of its dependent or related objects get notified automatically
Real Life Example:
Group Chat is a real life example of observer pattern. Whenever someone type some text in text button and hit send button. Every member get notified that someone texted in group.
Java Code Example:
public interface Subject { void register(Observer observer); void remove(Observer observer); void notifyRespectedObserver(String msg); } public interface Observer { void update(String msg); String write(String msg); String getName(); } public class Console implements Subject { public ListmemberList; public Console(){ memberList = new LinkedList (); } public void register(Observer observer){ memberList.add(observer); } public void remove(Observer observer){ memberList.remove(observer); } public void notifyRespectedObserver(String msg){ for(Observer observer:memberList){ observer.update(observer.getName()+": $"+msg); } } } public class GroupMember implements Observer{ private String name; public GroupMember(String name){ this.name = name; } @Override public void update(String msg){ System.out.println(msg); } public String write(String msg){ return this.name+"@ "+msg; } //Getters and Setters public String getName() { return name; } public void setName(String name) { this.name = name; } } public class ChatGroup { public static void main(String... args){ Console console = new Console(); Observer ram = new GroupMember("Ram"); Observer shyam = new GroupMember("Shyam"); Observer rohan = new GroupMember("Rohan"); Observer sohan = new GroupMember("Sohan"); console.register(ram); console.register(shyam); console.register(rohan); console.register(sohan); //Some one write in text box String text = rohan.write("Hi friends how r u!"); console.notifyRespectedObserver(text); } }
Comments
Post a Comment