Skip to content

Instantly share code, notes, and snippets.

@LeandrodeLimaC
Created November 23, 2021 13:52
Show Gist options
  • Save LeandrodeLimaC/79ee01eca3470c695dad59a1d5372fff to your computer and use it in GitHub Desktop.
Save LeandrodeLimaC/79ee01eca3470c695dad59a1d5372fff to your computer and use it in GitHub Desktop.
Observer.ts
// 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