Home > other >  Does the Observer Design Pattern Work For Food Delivery Status Updates?
Does the Observer Design Pattern Work For Food Delivery Status Updates?

Time:05-11

I've recently been learning about the Observer design pattern and understand canonical examples like newspapers notifying their subscribers like so:

public class NewsPaper implements Publisher{
    List<Subscriber> subscribers;

    @Override
    public void register(Subscriber s) {
        this.subscribers.add(s);
    }

    @Override
    public void unregister(Subscriber s) {
        this.subscribers.remove(s);
    }

    @Override
    public void update(String type) {
        this.subscribers.forEach(subscriber -> subscriber.update()));
    }
}

I was thinking about how something like this would translate to a food delivery notification service where each delivery needs to be notified separately. For example the delivery status would send updates when the order is "on the way", "arriving", ect. Is there a way to apply the observer problem (or another design pattern) to notification services like food delivery?

A map could be used to map each delivery order to the subscribers, but this seemed inefficient since it most likely would be a one -> one relationship.

CodePudding user response:

Normally observer observable design pattern is used when there is a one to many relationship between objects because the basic idea of this design pattern is to notify about the state change of the observable object to all the observers who are observing that observable object.

But according to your problem there is a one to one relationship.(One order - One person).

But if you want to use observer design pattern, you can use it. Then your observer array will contain only one element.(Only the owner of that particular order)

Alternative way,

You can create an order object with the customer object as an attribute of it, when the order is place by the customer. (You can add the customer to the order object through the constructor of the order object, when it is created)

Then when the status of the order object is changed,

  1. You can have a one method to notify the customer. If you are using one method you can use enum to store the possible status of the order. Then according to the status of the order you can call the method with the relevant status.
  2. You can have multiple methods for notifying each status of the order. It means one method for each status.

But I think first method is better because if you have to add some extra status later, you only need to add that status to the enum. But if you use the second method you need to add separate method for this.

  • Related