Advertisement




Observer Design Pattern

What is Observer Design Pattern?

  • It falls under behavioral design pattern.
  • Object (Subject) maintains all its dependents called observers.
  • The main aim of Observer Design Patterns is one to many dependencies between objects. One object changes state, and all its dependents are notified and updated automatically.
  • Observer Design Pattern is also called Listener Design Pattern.
  • Subject (Publisher) doesn’t need to know anything about the observers (subscriber or listeners).
  • Very loose coupling
  • Limitation: Subject (Publisher) may send updates that may don’t make sense to the observers (listeners).

Real Life Examples of Observer Design Pattern

Example 1:

online shopping site exampleLet's consider an online shopping website. If you are willing to buy an electrical gadget which is in huge demand, you have to wait till the product is available. Since you are very eager to buy this product so you will register it on that site. If that product is available, the site will notify you either by mail or message. Here, you are the observer. Similarly, many observers are eager to buy that product. Here, observers won't have information of other observers, but the online shopping site (Subject) knows information about all the observers. The subject has information like Phone number, email id of all the observers. Whenever the product is available, the subject sends the notification to all the observers.

UML Class Diagram of Observer Design Pattern

Observer Design Pattern Java Implementation

Step:

public class Socket
{

    public Voltage getVoltage()
    {
        return new Voltage(240); //In India 240 is the default voltage
    }
}

Tutorial Videos of Observer Design Pattern

For tutorial videos, please check out the premium Software Design Pattern course on Udemy.  

Advertisement




Advertisement




Advertisement