vendredi 30 décembre 2022

Observer pattern on all instances of class

I'm trying to learn about the observer pattern, and a case I had thought of is that I want to observe when any instance of a class gets updated, rather than just a singleton. An example I put together is that we have a DeliverySystem observer that wants to know when any Burger is cooked. We could try to accomplish this with the following:

class Burger {
    static observers: Observer[] = [];

    static addObserver(observer: Observer) {
        Burger.observers = Burger.observers.concat(observer);
    }

    id: number;

    constructor(id: number) {
        this.id = id;
    }

    cook() {
        Burger.observers.forEach(observer => observer.update(this));
    }
}

interface Observer {
    update: (target: any) => void;
}

class DeliverySystem implements Observer {
    update(target: any) {
        console.log("DeliverySystem got pizza " + target.id);
    }

    observe() {
        Burger.addObserver(this);
    }
}


const deliverySystem = new DeliverySystem().observe();
new Burger(12345).cook();

This generally works, but I'm not sure how to expand this so that my DeliverySystem can observe other foods. If I add a Hotdog class, what interface can Burger and Hotdog both implement that will allow me to avoid each needing to handle their observers independently? I would like to be able to write Burger like the following, but I'm not really sure how:

class Burger implements Observable /* <-- what does this look like? */ {
    id: number;

    constructor(id: number) {
        this.id = id;
    }

    cook() {
        updateObservers(this);
    }
}

Aucun commentaire:

Enregistrer un commentaire