mardi 30 mai 2023

Implementing Facade pattern using Java Interfaces

Currently, I have classes in my module represented by the class diagram below. RestaurantService is a façade interface that is composed of other services like ReservationService and KitchenService. Scope for ReservationService class and KitchenService class is default to hide their visibility from client. From encapsulation perspective this works fine, clients are only aware of RestaurantService and have no knowledge of the internal services. enter image description here

Package Structure

enter image description here

public class RestaurantServiceImpl implements RestaurantService {

   private KitchenService kitchenService;
   private ReservationService reservationService;

   @Override
   public void bookTable(){
      this.reservationService.bookTable();
   }

   @Override
   public OrderDto placeOrder() {
      boolean orderAccepted = this.kitchenService.acceptOrder();
      
      .........
   }

   .........
}

class KitchenService {

   public boolean acceptOrder(){
      .........
   }
}

class ReservationService {

   public void bookTable(){
      .........
   }
}

Now, I want to replace internal service classes with interfaces something like below. enter image description here

With this new design the internal services become public since I can't use protected with Java Interfaces. Therefore, by design there is nothing stopping the client from directly accessing the internal services. Which would lead to two obvious problems:

  1. How will the client know whether it should call bookTable() from RestaurantService or ReservationService.
  2. Leading to fragile code when individual developers decide to call internal service directly rather than using the façade.

So, my question is how to use Java Interfaces for internal services without losing on encapsulation.

I also think this is not a subjective question but more of a design problem for which I am sure there must a design pattern. Therefore, want to learn how you guys handle this in your projects.

Thanks. Looking forward to your inputs.

Aucun commentaire:

Enregistrer un commentaire