eaglewap Data Scientist | Software Engineer | Google Code U Alumni | Former WSO2 Software Engineering Intern | "Google Code U"Alumni | Former WSO2 Software Engineering Intern. No comments

Observer Design Pattern


  • Also Known as Dependents, Publish-Subscribe
  • Use when there is one to many relationship between objects and if one object is modified, its dependent objects are notified
  • The change of a state in one object is reflected in another object without keeping the objects tightly coupled
  • The framework can be easily enhanced in future with new observers with minimal changes
  • View part of the ‘model-view-controller’
  • Extensively used in event management


Class diagram for Observer Design Pattern

Observer 

A way of notifying change to a number of classes
It falls under the category of Behavioral Patterns.

Class diagram for Observer Design Pattern

Example Java Code for Observer 😊

Let's take a scenario where people subscribe to the items to a shop.

Usually, when there's item out of stock people go shopping day by day and ask whether it arrived or not. It's not good in user's point of view.

So the shop owner decided to use the Observer pattern to resolve this issue.


  • Before analyzing the code go to Demo class and have a look at what is happening there!

In observer Observable pattern there will be an array list or Hashmap to hold the item.


Here observers are person who subscribed to the shop for the item

The update() method is used in Observer to update what happened in the shop.

Note that why we are using the Observer and Observable as a separate interface rather than writing the methods to each class is to enforce the coder to write the methods.
If you are consistent enough to write relevant methods then you don't need to write Observer, Observable interface.

Observer.java
1
2
3
4
public interface Observer {
    Void update (String s);// Getting a parameter as a string
}

Person.Java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public class Person implements Observer{
     String name; //Person has an attribute name
     
     public Person (String name){
           this.name=name;
     
     }

    @Override
    public Void update(String s) {
        System.out.println(s); //Person has method to print the string when item is available
         return null;
    }

    public String getName() {
        return name; //getter for name
    }
  

}

Observavle.java
1
2
3
4
5
6
public interface Observable {
    void attach(Observer o,String item);
    void detach(Observer o);
    void notify(Item item);
}



Shop.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class Shop implements Observable {

    //Array list to hold the items Eg: TV, fridge...
    private final ArrayList <Item> items;
    
    //Hashmap to hold the Observer and the Item name
    private HashMap<Observer,String> hm;

    //Constructor of this class
    public Shop() {
        items =new ArrayList<>();
        hm=new HashMap<Observer,String>();

    }
    
    public void additem(Item item){
        //Whenthe item is added the notify method will be called
        items.add(item);

        notify(item);
    }

    @Override
    public void attach(Observer o,String item) {
        //Adding item to hash map
        hm.put(o,item);
      
    }

    @Override
    public void detach(Observer o) {
        //Deleting item from hash map
        hm.remove(o);
       
    }

    @Override
   public void notify(Item item) {
 for(Map.Entry<Observer, String> entry : hm.entrySet()){   
          if(item.getItemname().equalsIgnoreCase(entry.getValue())) {
  Person pers = (Person) entry.getKey();
  pers.update( item.getItemname()+ " is available : Notifying to: "+ pers.getName());
    }
 }
     }  
}


Item.java
This class is to hold the items  Eg: TV, Fridge

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public class Item {
    String itemname;

    public Item(String itemname) {
        this.itemname=itemname;
    }

    public String getItemname() {
        return itemname;
    }

}


Demo.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Demo {
    public static void main(String[] args) {
        //Creating new Shp object
        Shop shop = new Shop();

        //Creating persons who is gong to sbscribe to shop
        Person jhon =new Person ("Jhon");
        Person jhese =new Person ("jhese");
        Person kugan =new Person ("kugan");

        //Creating items available to shop
        Item tv = new Item("TV");
        Item fridge = new Item("Fridge");

        //Subscribing to Shop with name and wanted items to the shop
        shop.attach(jhon,"TV");
        shop.attach(jhese,"Fridge");
        shop.attach(kugan,"TV");

       //Adding Tvto the shop then the person who subscribed for tv will be notified
        System.out.println("Adding TV To the shop::");
        shop.additem(tv);

        //Adding fIRDGE to the shop then the person who subscribed to FRIDGE will be notified
        System.out.println("Adding Fridge To the shop::");
        shop.additem(fridge);
    }          
}

Comments (0)

Post a Comment

Cancel