In many programs there will be an action taken only when something else has changed. For example, if there was a security app, you would not want it to continuously send you alerts that everything is fine, only when there is an actual emergency. This is where observers come in handy and in specific observer design patterns. Imagine you were creating an alarm system for inclement weather. Whenever there was inclement weather, an alarm would sound, a alarm message would appear on a phone, etc. Without observers, a person would need to run a clock that constantly checks for updates in the weather. By doing so in this process, there is a big strain on hardware. Observers send a signal when there is an update and does not require the constant checking for updates. When using observers, the design pattern should be set up such that there exists an interface called subject. This subject interface will be used to register and unregister observers, notify observers and get an update from the subject. The next interface will be the Observer interface which will contain an update method for the observer and a setSubject method, which is used to attach the subject to the observer. From here you will be able to implement these two interfaces. While implementing the Subject interface you will be able to create a class that overrides register, unregister and update the observer. When implementing the Observer interface, you will be able to override the update which allows for you to implement what the observer needs to be checking for. This allows for the user to have control over what the system is checking for. When that observer notices a change, it will be able to send a signal down to whatever class has extended subject and send out whatever notice must be sent when this event is triggered. By using this type of design pattern, the user is allowed to be very flexible while saving strain on the hardware that would normally be placed there by clocks. Many API’s use this type of design because as mentioned before, if an API had to have a clock running that was checking if someone had pressed a button every so-often, it would be chaos. The API is able to implement an observer for the buttons and when that button is pressed it updates the subject and executes whatever that button was programmed to do. This website gives a great breakdown of the design pattern and how to implement it.

Observer Design Pattern in Java

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create your website at WordPress.com
Get started
%d bloggers like this: