Skip to content

Instantly share code, notes, and snippets.

@sammieboy97
Created November 14, 2020 18:24
Show Gist options
  • Save sammieboy97/f4397fa682977a26d51d8acdcf3a450b to your computer and use it in GitHub Desktop.
Save sammieboy97/f4397fa682977a26d51d8acdcf3a450b to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
interface Subject {
public void registerObserver(Observer observer);
public void removeObserver(Observer observer);
public void notifyAllObservers();
}
class DataStore implements Subject{
private ArrayList<Observer> observers;
public DataStore() {
this.observers = new ArrayList<>();
}
@Override
public void registerObserver(Observer observer) {
this.observers.add(observer);
}
@Override
public void removeObserver(Observer observer) {
int index = this.observers.indexOf(observer);
if(index >= 0) {
this.observers.remove(index);
}
}
@Override
public void notifyAllObservers() {
for(Observer observer: this.observers) {
observer.update();
}
}
public void dataChanged() {
notifyAllObservers();
}
public void setData() {
// We can set data in this object as needed.
dataChanged();
}
}
interface Observer {
public void update();
}
class GraphView implements Observer{
private Subject dataStore;
public GraphView(Subject dataStore) {
this.dataStore = dataStore;
dataStore.registerObserver(this);
}
@Override
public void update() {
//Change the state of this object as needed here
System.out.println("Update called in GraphView");
}
}
class GridView implements Observer{
private Subject dataStore;
public GridView(Subject dataStore) {
this.dataStore = dataStore;
dataStore.registerObserver(this);
}
@Override
public void update() {
//Change the state of this object as needed here
System.out.println("Update called in GridView");
}
}
public class ObserverPattern {
public static void main(String[] args) {
DataStore dataStore = new DataStore();
Observer graphView = new GraphView(dataStore);
Observer gridView = new GridView(dataStore);
//More and more views can be added here if neededd
System.out.println("Before change of state in observer");
dataStore.setData(); //Some data to be passed.
System.out.println("After change of state in observer");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment