Skip to content

Instantly share code, notes, and snippets.

@davidalves1
Last active August 2, 2023 14:32
Show Gist options
  • Save davidalves1/ff589501d727c48f68c8d2795d72f7ea to your computer and use it in GitHub Desktop.
Save davidalves1/ff589501d727c48f68c8d2795d72f7ea to your computer and use it in GitHub Desktop.
Observer Pattern
interface Observer {
update: (s: Subject) => void
}
class Subject {
private observers: Observer[] = [];
addObserver(ob: Observer) {
if (!this.observers.some(obs => obs === ob)) {
console.log('ADDING:', ob);
this.observers.push(ob);
}
}
removeObserver(ob: Observer) {
console.log('REMOVING:', ob);
this.observers = this.observers.filter(obs => obs !== ob );
}
notifyObservers() {
this.observers.map(ob => ob.update(this))
}
}
class Temperature extends Subject {
private temp: number;
getTemp() {
return this.temp;
}
setTemp(value: number) {
this.temp = value;
this.notifyObservers();
}
}
class TempFahrenheit implements Observer {
update(s: Subject) {
const temp = (s as Temperature).getTemp();
document.querySelector("#tempF").innerHTML = `${(temp * 9 / 5) + 32} °F`;
}
}
class TempKelvin implements Observer {
update(s: Subject) {
const temp = (s as Temperature).getTemp();
document.querySelector("#tempK").innerHTML = `${temp + 273.15} K`;
}
}
function bootstrap() {
const t = new Temperature();
const tempF = new TempFahrenheit()
const tempK = new TempKelvin()
t.addObserver(tempF)
t.addObserver(tempK)
document.querySelector("#sync").addEventListener('click', () => {
const value = Number(document.querySelector("#tempValue").value || 0;
t.setTemp(value);
});
document.querySelector("#addObserverF").addEventListener('click', () => {
t.addObserver(tempF);
});
document.querySelector("#removeObserverF").addEventListener('click', () => {
t.removeObserver(tempF)
});
}
bootstrap();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<div>
<input type="text" id="tempValue">
<button id="sync">Sincronizar</button>
</div>
<div>
<p>Temperatura em Fahrenheit: <span id="tempF">0 °F</span></p>
<button id="addObserverF">Add</button>
<button id="removeObserverF">Remover</button>
</div>
<p>Temperatura em Kelvin: <span id="tempK">0 K</span></p>
</div>
<script src="dist/app.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment