Observer Pattern Principle

Observer Pattern :
Defines a one-to-many dependency between objects. When an object's state changes, all objects that depend on it are notified and automatically updated.

1. In the stock market, stock data changes at any time. Sellers and buyers can see changes at any time.



StockData.java

package com.observer.principle;

import java.util.Observable;
import java.util.Observer;

public class StockData extends Observable {
    private float price;

    public StockData(float price) {
        super();
        this.price = price;
    }

    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }

    public void setStockData(float price) {
        this.price = price;
        setChanged();
        notifyObservers();
    }

}



Buyer.java

package com.observer.principle;

import java.util.Observable;
import java.util.Observer;
  
public class Buyer implements Observer
{
      
    public Buyer(Observable o)
    {
        o.addObserver(this);
    }
  
    @Override
    public void update(Observable o, Object arg)
    {
        if(o instanceof StockData)
        {
            StockData data=(StockData)o;
            System.out.println("Buyer Price:"+data.getPrice());
        }
    }
  
}



Seller.java

package com.observer.principle;

import java.util.Observable;
import java.util.Observer;
  
public class Seller implements Observer
{
      
    public Seller(Observable o)
    {
        o.addObserver(this);
    }
  
    @Override
    public void update(Observable o, Object arg)
    {
        if(o instanceof StockData)
        {
            StockData data=(StockData)o;
            System.out.println("Seller Price:"+data.getPrice());
        }
    }
  
}



2. Create a Test class : TestObserver.java

package com.observer.principle;

public class TestObserver {

    public static void main(String[] args) {
        StockData data = new StockData(16.9f);

        Buyer buyer = new Buyer(data);
        Seller seller = new Seller(data);
        
        data.setStockData(18.9f);
        
        System.out.println("------------------------");
        
        data.setStockData(12.9f);
    }

}



Result:



Easy Learning Java


Easy Learning Design Patterns Java Practice


Easy Learning Data Structures & Algorithms Java Practice


Java Parsing Collection XML JSON


Easy Learning JDBC + MySQL


Easy Learning Javascript


Easy Learning Design Patterns Javascript


Easy Learning Design Patterns ES6+ Javascript


Easy Learning Data Structures & Algorithms Javascript


Easy Learning Data Structures & Algorithms ES6+Javascript


Easy Learning Oracle SQL


Easy Learning JDBC + Oracle


Easy Learning Python 3


Easy Learning Data Structures & Algorithms Python 3


Easy Learning Design Patterns Python 3


Easy Learning MySQL SQL


Easy Learning HTML CSS

Observer Pattern Principle