This is the third design pattern which deals with behavioral design.It has a subject and observers. Subject is the object and observers are the dependents. When a change occurs it reflects the observers.
Let us write a java program to implement this design
pattern.
Steps:
- · Create an interface observer with a method updateIt with a string msg.
- · Write a code for subject class with observer array and four member functions. One for insertObserver, removing observer,notify the observer and display the state information.
- · Implement a concreteObserver to implement observer.
- · Override the updateIt() function.
- · Finally, create the main() function for creating objects and function calling.
#Java Program to implement Observer Design Pattern
import java.util.ArrayList;
import java.util.List;
interface Observer {
void
updateIt(String msg);
}
private
List<Observer> obs = new ArrayList<>();
private String
stateInfo;
obs.add(observer);
}
obs.remove(observer);
}
this.stateInfo
= stateInfo;
notifyObservers();
}
for (Observer
observer : obs) {
observer.updateIt(stateInfo);
}
}
}
private String
name;
this.name =
name;
}
public void
updateIt(String stateInfo) {
System.out.println(name + " received state change: " +
stateInfo);
}
}
public static void
main(String[] args) {
Subject
subject = new Subject();
Observer observer1 = new ConcreteObserver("Observer 1");
Observer
observer2 = new ConcreteObserver("Observer 2");
subject.InsertObserver(observer1);
subject.InsertObserver(observer2);
subject.setState("State 1");
subject.setState("State 2");
}
}
While executing this program, you will get the below output.
C:\raji\blog>javac Main19.java
C:\raji\blog>java Main19
Observer 1 received state change: State 1
Observer 2 received state change: State 1
Observer 1 received state change: State 2
Observer 2 received state change: State 2
Thus the program to implement the observer design pattern is
executed. Happy Coding!!!!
No comments:
Post a Comment