Created
September 16, 2019 13:54
-
-
Save mtov/5fadb0e599cb84fd6bd124b2ff37c03c to your computer and use it in GitHub Desktop.
Observer (Design Pattern)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.List; | |
import java.util.ArrayList; | |
import java.util.Iterator; | |
class Subject { | |
private List<Observer> observers = new ArrayList<Observer>(); | |
public void addObserver(Observer observer) { | |
observers.add(observer); | |
} | |
public void removeObserver(Observer observer) { | |
observers.remove(observer); | |
} | |
public void notifyObservers() { | |
Iterator it = observers.iterator(); | |
while (it.hasNext()) { | |
Observer obs= (Observer) it.next(); | |
obs.update(this); | |
} | |
} | |
} | |
interface Observer { | |
public void update(Subject s); | |
} | |
class Temperatura extends Subject { | |
private double temp; | |
public double getTemp() { | |
return temp; | |
} | |
public void setTemp(double temp) { | |
this.temp = temp; | |
notifyObservers(); | |
} | |
} | |
class TermometroCelsius implements Observer { | |
public void update(Subject s) { | |
double temp = ((Temperatura) s).getTemp(); | |
System.out.println("Temperatura Celsius: " + temp); | |
} | |
} | |
public class Main { | |
public static void main(String [] args) { | |
Temperatura t = new Temperatura(); | |
t.addObserver(new TermometroCelsius ()); | |
t.setTemp(100.0); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment