Skip to content
APPCITORThe Tech Blog
Esc

Behavioral – Observer Design Pattern

August 6, 2020 2 min read

Behavioral – Observer Design Pattern

Observer pattern is classified among Behavioral patterns. This pattern is using if there is a many-to-many relationship between the objects inside a program. That means when a behavior of one object is affecting to many other objects inside the program.  

Let’s check it out from an example in java.

This is on a salary calculation between managers and employees.

Here I created a class called “Salary” first and made a list to add observers to the list. Because “Salary” is the main object that keeps the observers with it. But to add those observers I should make “Observer” class.

After creating the observer class, let’s go again to the “Salary” class. There you can see the method “attach()”. From this method I can add observers to the list. Then I created another variable called “value” to keep the real salary and by including the getters and setters I made it as a property.

You can see I called a method called “notifyAllObervers()” method inside the “getValue()” method. “notifyAllOberver” method is created here to iterate the observers as we know for each observer “update()” method  is given by the class “Observer”.

Here I created 2 classes called “ManagerBonus” and “EmployeeBonus” by extending from the abstract class “Observer” as they are the observer classes that observe the main object. If we change the salary value in any time, those 2 classes update their salaries by the “update()” method that is overridden. This is the importance of using observer design pattern. Let’s go to the main method.

You can change value of salary and see the output. Below you can see the output coming for the above program.

You can visit the below given articles to learn about creational design patterns and Structural Design Patterns.

Thank you.

Creational Design Patterns

Singleton Design Pattern

Factory Design Pattern

Abstract Factory Design Pattern

Prototype Design Pattern

Builder Design Pattern

Structural Design Patterns

Facade Design Pattern

Decorator Design Pattern

Adapter Design Pattern

Bridge Design Pattern

Composite Design Pattern

Proxy Design Pattern

Flyweight Design Pattern

Share this article

Keep reading