Created
July 17, 2021 03:11
-
-
Save LeandrodeLimaC/9f1eb32def4b871150ec8cf4c0bd8e5d to your computer and use it in GitHub Desktop.
Observer
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
interface Observer { | |
update: () => void; | |
} | |
interface Subject { | |
subscribe: (observer: Observer) => void, | |
unsubscribe: (observer: Observer) => void, | |
notify: () => void, | |
} | |
interface IWeatherStation extends Subject { | |
updateTemperature: (value: number) => void, | |
} | |
const WeatherStation = (): IWeatherStation => { | |
let temperature = 0 | |
let observers: Observer[] = [] | |
const updateTemperature = (value) => { | |
temperature = value | |
notify() | |
} | |
const subscribe = (observer) => observers.push(observer) | |
const unsubscribe = (observer) => observers = observers.filter(o => o !== observer) | |
const notify = () => observers.forEach(o => o.update()) | |
return { | |
updateTemperature, | |
subscribe, | |
unsubscribe, | |
notify, | |
} | |
} | |
const Cooler = (name: string): Observer => { | |
const state = { name } | |
return{ | |
update: () => console.log("Realizando checks de ventilação...", state.name) | |
} | |
} | |
const Display = (): Observer => { | |
return{ | |
update: () => console.log("Recebi a atualização") | |
} | |
} | |
const weatherStation = WeatherStation() | |
const cooler1 = Cooler('cooler1') | |
const cooler2 = Cooler('cooler2') | |
const cooler3 = Cooler('cooler3') | |
const display = Display() | |
weatherStation.subscribe(cooler1) | |
weatherStation.subscribe(cooler2) | |
weatherStation.subscribe(cooler3) | |
weatherStation.subscribe(display) | |
weatherStation.updateTemperature(10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment