Created
November 23, 2021 13:52
-
-
Save LeandrodeLimaC/79ee01eca3470c695dad59a1d5372fff to your computer and use it in GitHub Desktop.
Observer.ts
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
// Comportamental - Como os objetos dependentes se mantem atualizados | |
interface Observer { | |
update: () => void | |
} | |
interface Subject { | |
attach: (observer: Observer) => void, | |
detach: (observer: Observer) => void, | |
notify: () => void, | |
} | |
interface WeatherStation extends Subject { | |
updateTemperature: (value: number) => void | |
} | |
const WeatherStation = () : WeatherStation => { | |
const state = { | |
temperature: 0 | |
} | |
let observers: Observer[] = [] | |
const attach = (observer: Observer) => observers.push(observer) | |
const detach = (observer: Observer) => observers = observers.filter(o => o !== observer) | |
const notify = () => observers.forEach(o => o.update()) | |
const updateTemperature = (value: number) => { | |
state.temperature = value | |
notify() | |
} | |
return { | |
attach, | |
detach, | |
notify, | |
updateTemperature | |
} | |
} | |
const Cooler = (name: string): Observer => { | |
const state = { name } | |
const update = () => { | |
console.log(` | |
Atualização de temperatura detectada! | |
Realizando checks de ventilação no ${state.name}... | |
`) | |
} | |
return { update } | |
} | |
const weatherStation = WeatherStation() | |
const cooler1 = Cooler('Cooler 1') | |
weatherStation.attach(cooler1) | |
weatherStation.updateTemperature(10) | |
weatherStation.updateTemperature(5) | |
weatherStation.detach(cooler1) | |
weatherStation.updateTemperature(5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment