diff --git a/src/learn/simple_observer/ConcreteObserver.java b/src/learn/simple_observer/ConcreteObserver.java new file mode 100644 index 0000000..831179e --- /dev/null +++ b/src/learn/simple_observer/ConcreteObserver.java @@ -0,0 +1,15 @@ +package learn.simple_observer; + +public class ConcreteObserver implements Observer { + private ConcreteSubject subject; + + public ConcreteObserver(ConcreteSubject subject) { + this.subject = subject; + subject.registerObserver(this); + } + + @Override + public void update() { + System.out.println("Observer was notified: subject has new state: " + subject.getState()); + } +} diff --git a/src/learn/simple_observer/ConcreteSubject.java b/src/learn/simple_observer/ConcreteSubject.java new file mode 100644 index 0000000..d00c83c --- /dev/null +++ b/src/learn/simple_observer/ConcreteSubject.java @@ -0,0 +1,37 @@ +package learn.simple_observer; + +import java.util.ArrayList; +import java.util.List; + +public class ConcreteSubject implements Subject { + private List observers = new ArrayList<>(); + int state; + + @Override + public void registerObserver(Observer o) { + observers.add(o); + } + + @Override + public void removeObserver(Observer o) { + observers.remove(o); + } + + @Override + public void notifyObservers() { + for (Observer o : observers) { + o.update(); + } + } + + public void setState(int state) { + this.state = state; + if (state > 50) { + notifyObservers(); + } + } + + public int getState() { + return state; + } +} diff --git a/src/learn/simple_observer/Main.java b/src/learn/simple_observer/Main.java new file mode 100644 index 0000000..0a297e4 --- /dev/null +++ b/src/learn/simple_observer/Main.java @@ -0,0 +1,12 @@ +package learn.simple_observer; + +public class Main { + public static void main(String[] args) { + ConcreteSubject subject = new ConcreteSubject(); + Observer observer = new ConcreteObserver(subject); + subject.setState(40); + subject.setState(100); + Observer observer2 = new ConcreteObserver(subject); + subject.setState(200); + } +} diff --git a/src/learn/simple_observer/Observer.java b/src/learn/simple_observer/Observer.java new file mode 100644 index 0000000..fa969f5 --- /dev/null +++ b/src/learn/simple_observer/Observer.java @@ -0,0 +1,5 @@ +package learn.simple_observer; + +public interface Observer { + void update(); +} diff --git a/src/learn/simple_observer/Subject.java b/src/learn/simple_observer/Subject.java new file mode 100644 index 0000000..78bb15d --- /dev/null +++ b/src/learn/simple_observer/Subject.java @@ -0,0 +1,7 @@ +package learn.simple_observer; + +public interface Subject { + void registerObserver(Observer o); + void removeObserver(Observer o); + void notifyObservers(); +}