Implementing Observer pattern

This commit is contained in:
Yewon Kim 2025-05-18 23:13:54 +09:00
parent 71aeb0057a
commit df9229cb78
5 changed files with 52 additions and 3 deletions

View File

@ -13,12 +13,12 @@ The Gun is the mouse. To draw it, hide the cursor with the noCursor function and
class Gun extends Subject {
constructor(totalShots) {
constructor(totShots) {
super();
this.cursorImg = null;
this.shotSound = null;
this.emptySound = null;
this.remainingShots = totalShots;
this.remainingShots = totShots;
this.bullets = []; // array of Bullet objects
}

View File

@ -38,6 +38,16 @@ class ScoreDisplay {
}
}
update(source, ...others) {
if (source === 'gun') {
const [, , remainingShots] = others;
this.shotLeft = remainingShots;
} else if (source === 'target-hit') {
const [points] = others;
this.score += points;
}
}
}
export { ScoreDisplay };

View File

@ -1,5 +1,27 @@
class Subject {
// TO DO
constructor() {
this.observers = [];
}
subscribe(observer) {
if (!observer || typeof observer.update !== 'function') return;
this.observers.push(observer);
}
unsubscribe(observer) {
this.observers = this.observers.filter(o => o !== observer);
}
unsubscribeAll() {
this.observers = [];
}
notifySubscribers(source, ...others) {
for (let observer of this.observers) {
observer.update(source, ...others);
}
}
}
export { Subject };

View File

@ -39,6 +39,15 @@ class Target extends Subject {
py >= this.y &&
py <= this.y + TARGET_WIDTH;
}
update(source, ...others) {
if (source === 'gun') {
const [x, y] = others;
if (this.contains(x, y)) {
this.hit();
}
}
}
}
class TeddyTarget extends Target {

View File

@ -20,6 +20,14 @@ function setup() {
// 2. Init the targets
initTargets();
// 3. Subscribe gun
gun.subscribe(score);
// Subscribe each target to gun
for (let target of targets) {
gun.subscribe(target);
target.subscribe(score);
}
}