Search code examples
javadesign-patternsservice-layerfacade

Difference between the facade pattern and service layer pattern


what exactly is the difference between the facade pattern and service layer pattern?

For facade patterns you can find definitions like: A facade encapsulates a complex subsystem behind a simple interface. It hides much of the complexity and makes the subsystem easy to use.

So a facade class encapsulates complex business logic into easy-to-use methods.

But is the service layer pattern not doing the same thing?


Solution

  • Facade is a structural design pattern. Service layer is an architectural design pattern. Service layer serves to organize the services so that services belonging to the same layer share functionality, therefore enforcing that related services are logically grouped and address a smaller set of activities. Facade provides an interface that masks a more complex underlying code, but it doesn't concern itself with how the services are organized.

    For example, imagine that you have a web shop. When you click the "buy" button, that might call a single buyProducts() method, but inside that method you might call a ProductAvailabilityService that tells you if the products you want to buy are still available, a PaymentService to actually manage the payment, and an EmailNotificationService to send you an email with the details of your purchase. This would be a facade.

    Now, imagine you have a hospital. And you have services to retrieve a patient's history, a patient's currently prescripted medicines, etc. Those might all belong to a Patient Services Layer. Whereas a service for a doctor to check what appointments they have might belong to a Doctor Services Layer.

    So in short, one pattern concerns itself with a logical organization of the services, and the other with simplifying how one or more services are used.