Skip to content

Observer pattern #14

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 33 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,33 @@
# DesignPatternsJava9
This repo consists Gang of Four Design patterns code on Java 9. Each branch in the repository has code of 1 design pattern. Switch repository to try out different design patterns.
# What is Observer Design Pattern
The observer pattern is a Behavioral design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes or updates.

## Diagram
![Diagram](https://github.com/premaseem/DesignPatternsJava9/blob/observer-pattern/diagrams/Observer-Pattern-class-diagram.png "Diagram")

![Diagram](https://github.com/premaseem/DesignPatternsJava9/blob/observer-pattern/diagrams/Observer-Design-Pattern-generic.jpeg "Diagram")

![Diagram](https://github.com/premaseem/DesignPatternsJava9/blob/observer-pattern/diagrams/ObserverSequenceDiagram.png "Diagram")

# When to use Observer Design Pattern
* Heavy used in "event driven" application
* It is suitable for any scenario that requires push-based notification.

### Learn Design Patterns with Java by Aseem Jain
This repository contains working project code used in video Course by Packt Publication with title "Learn Design Patterns with Java " authored by "Aseem Jain".

### Course link:
https://www.packtpub.com/application-development/learn-design-patterns-java-9-video

### ![ http://in.linkedin.com/in/premaseem](https://github.com/premaseem/DesignPatternsJava9/blob/master/linkedin.png "http://in.linkedin.com/in/premaseem") Profile: http://in.linkedin.com/in/premaseem

### Authors blog on design patterns:
https://premaseem.wordpress.com/category/computers/design-patterns/

### Software Design pattern community face book page:
https://www.facebook.com/DesignPatternGuru/

### Note:
* This code base will work on Java 9 and above versions.
* `diagrams` folders carry UML diagrams.
* `pattern` folder has code of primary example.
* `patternBonus` folder has code of secondary or bonus example.
Binary file added diagrams/Observer-Design-Pattern-generic.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added diagrams/Observer-Pattern-class-diagram.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added diagrams/ObserverSequenceDiagram.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
13 changes: 0 additions & 13 deletions pattern/src/com/premaseem/Client.java

This file was deleted.

76 changes: 76 additions & 0 deletions pattern/src/com/premaseem/client/ClientForShareTrading.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package com.premaseem.client;

/*
@author: Aseem Jain
@title: Design Patterns with Java 9
@link: https://premaseem.wordpress.com/category/computers/design-patterns/
*/

import java.util.Random;
import java.util.Scanner;

import com.premaseem.observable.SharePriceObservable;
import com.premaseem.observable.impl.AppleShares;
import com.premaseem.observable.impl.GoogleShares;
import com.premaseem.observer.ShareTraderObserver;
import com.premaseem.observer.impl.ShareTrader;

public class ClientForShareTrading {

public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
int repeatRunFlag = 1;
while (repeatRunFlag == 1) {

System.out.println("Share trading platform designed using Observer design pattern ");
System.out
.println("Notification service can be turned ON / OFF for multiple company's Share \n ");
ShareTraderObserver shareTrader = new ShareTrader();

SharePriceObservable appleShares = new AppleShares();
SharePriceObservable googleShares = new GoogleShares();

System.out
.println("Do you want to observe share price and get notification / updates of Apple inc. shares ? ");
System.out.println("Press 1 for yes and 0 or other digits for no ");
int appleShareWatch = scan.nextInt();
if (appleShareWatch == 1) {
appleShares.addObserver(shareTrader);
} else {
appleShares.removeObserver(shareTrader);
}

System.out
.println("Do you want to observe share price and get notification / updates of Google inc. shares ? ");
System.out.println("Press 1 for yes and 0 or other digits for no ");
int googleShareWatch = scan.nextInt();
if (googleShareWatch == 1) {
googleShares.addObserver(shareTrader);
} else {
googleShares.removeObserver(shareTrader);
}

System.out.println("Simulating price change in Stock Market ^^--__-_-^^ ");
simulateSharePriceChange(appleShares);
simulateSharePriceChange(googleShares);
System.out.println("========================================");
System.out
.println("Do you want to Re-run this program - Press 1 for yes and 0 or other digits to EXIT ");
repeatRunFlag = scan.nextInt();
}
}

public static void simulateSharePriceChange (
SharePriceObservable sharePriceObservable) {
Random rnd = new Random();
for (int i = 0; i < 3; i++) {
sharePriceObservable.setCurrentMarketPrice(rnd.nextInt());
}
}
}

/** Lesson Learnt
* Pooling or continuous monitoring is not required
* Loose coupling between Share trader (client-observer)
* and Share company (subject-observable)
* */
16 changes: 16 additions & 0 deletions pattern/src/com/premaseem/observable/SharePriceObservable.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.premaseem.observable;


import com.premaseem.observer.ShareTraderObserver;

public interface SharePriceObservable {

void addObserver (ShareTraderObserver shareTraderObserver);

void removeObserver (ShareTraderObserver shareTraderObserver);

void notifyObservers ();

// This is just a work around to simulate the price from client side
public void setCurrentMarketPrice (Integer currentMarketPrice);
}
46 changes: 46 additions & 0 deletions pattern/src/com/premaseem/observable/impl/AppleShares.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.premaseem.observable.impl;
/*
@author: Aseem Jain
@title: Design Patterns with Java 9
@link: https://premaseem.wordpress.com/category/computers/design-patterns/
*/

import java.util.ArrayList;

import com.premaseem.observable.SharePriceObservable;
import com.premaseem.observer.ShareTraderObserver;

public class AppleShares implements SharePriceObservable {

public ArrayList<ShareTraderObserver> shareTraders = new ArrayList<ShareTraderObserver>();
private Integer currentMarketPrice = 0;

@Override
public void addObserver (ShareTraderObserver shareTraderObserver) {
shareTraders.add(shareTraderObserver);

}

@Override
public void removeObserver (ShareTraderObserver shareTraderObserver) {
shareTraders.remove(shareTraderObserver);

}

@Override
public void notifyObservers () {
for (ShareTraderObserver shareBroker : shareTraders) {
shareBroker.notifyCurrentPrice(getCurrentMarketPrice(), " Apple Inc. ");
}

}

public Integer getCurrentMarketPrice () {
return currentMarketPrice;
}

public void setCurrentMarketPrice (Integer currentMarketPrice) {
this.currentMarketPrice = currentMarketPrice;
notifyObservers();
}
}
47 changes: 47 additions & 0 deletions pattern/src/com/premaseem/observable/impl/GoogleShares.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package com.premaseem.observable.impl;

/*
@author: Aseem Jain
@title: Design Patterns with Java 9
@link: https://premaseem.wordpress.com/category/computers/design-patterns/
*/

import java.util.ArrayList;

import com.premaseem.observable.SharePriceObservable;
import com.premaseem.observer.ShareTraderObserver;

public class GoogleShares implements SharePriceObservable{

public ArrayList<ShareTraderObserver> shareTraders = new ArrayList<ShareTraderObserver>();
private Integer currentMarketPrice=0;

@Override
public void addObserver(ShareTraderObserver shareTraderObserver) {
shareTraders.add(shareTraderObserver);

}

@Override
public void removeObserver(ShareTraderObserver shareTraderObserver) {
shareTraders.remove(shareTraderObserver);

}

@Override
public void notifyObservers() {
for(ShareTraderObserver shareBroker : shareTraders){
shareBroker.notifyCurrentPrice(getCurrentMarketPrice()," Google Inc. ");
}

}

public Integer getCurrentMarketPrice() {
return currentMarketPrice;
}

public void setCurrentMarketPrice(Integer currentMarketPrice) {
this.currentMarketPrice = currentMarketPrice;
notifyObservers();
}
}
7 changes: 7 additions & 0 deletions pattern/src/com/premaseem/observer/ShareTraderObserver.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.premaseem.observer;

public interface ShareTraderObserver {

public void notifyCurrentPrice (Integer shareLatestPrice, String shareCompanyName);

}
20 changes: 20 additions & 0 deletions pattern/src/com/premaseem/observer/impl/ShareTrader.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.premaseem.observer.impl;
/*
@author: Aseem Jain
@title: Design Patterns with Java 9
@link: https://premaseem.wordpress.com/category/computers/design-patterns/
*/

import com.premaseem.observer.ShareTraderObserver;

public class ShareTrader implements ShareTraderObserver {

@Override
public void notifyCurrentPrice(Integer shareLatestPrice,
String shareCompanyName) {
System.out.println();
System.out.println(this.getClass().getSimpleName() + " received notification for Price change ");
System.out.printf("Price change notification - current price of %S Share is %d", shareCompanyName,shareLatestPrice);
System.out.println();
}
}
15 changes: 15 additions & 0 deletions pattern/src/com/premaseem/observer/impl/ShareTrader1.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.premaseem.observer.impl;

import com.premaseem.observer.ShareTraderObserver;

public class ShareTrader1 implements ShareTraderObserver {

@Override
public void notifyCurrentPrice(Integer shareLatestPrice,
String shareCompanyName) {
System.out.println();
System.out.println(this.getClass().getSimpleName() + ": Notified $$ ");
System.out.printf("Latest price of %S Share is %d ", shareCompanyName,shareLatestPrice);
System.out.println();
}
}
14 changes: 14 additions & 0 deletions pattern/src/com/premaseem/observer/impl/ShareTrader2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.premaseem.observer.impl;

import com.premaseem.observer.ShareTraderObserver;

public class ShareTrader2 implements ShareTraderObserver {
@Override
public void notifyCurrentPrice(Integer shareLatestPrice,
String shareCompanyName) {
System.out.println();
System.out.println(this.getClass().getSimpleName() + ": Notified $$ ");
System.out.printf("Latest price of %S Share is %d ", shareCompanyName,shareLatestPrice);
System.out.println();
}
}
13 changes: 0 additions & 13 deletions patternBonus/src/com/premaseem/Client.java

This file was deleted.

54 changes: 54 additions & 0 deletions patternBonus/src/com/premaseem/ClientJavaApi.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package com.premaseem;
/*
@author: Aseem Jain
@title: Design Patterns with Java 9
@link: https://premaseem.wordpress.com/category/computers/design-patterns/
*/

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

public class ClientJavaApi {

public static void main(String[] args) {

// Created subject
Subject subject = new Subject();

// Created Observer
Observer observer = new Observer() {
public void update(Observable obj, Object arg) {
System.out.println("Observer notified with update: " + arg);
}
};

// registered observer to the subject
subject.addObserver(observer);

System.out.println("Make text updates in subject: ");
new Thread(subject).start();
}
}

class Subject extends Observable implements Runnable {
public void run() {

// Every time whenever there is an update in subject,
// observer will be notified
while (true) {
String update = new Scanner(System.in).next();
setChanged();
notifyObservers(update);
}
}
}

/** Lesson Learnt
*
* 1. Instead of creating our own observer and observable,
* using (java.util) Java api's implementation of observer and observable
*
* 2. Java 9 has deprecated above apis, WHY ?
* answer is in link -https://stackoverflow.com/questions/46380073/observer-is-deprecated-in-java-9-what-should-we-use-instead-of-it
* */