-
-
Notifications
You must be signed in to change notification settings - Fork 26.8k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Browse the repository at this point in the history
* implementation of session facade #1278 * minor change * readme updated * addressed the comments regarding changing lists to maps and adding maven assembly plugin --------- Co-authored-by: Ilkka Seppälä <[email protected]>
- Loading branch information
Showing
17 changed files
with
1,180 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,157 @@ | ||
--- | ||
title: "Session Facade Pattern in Java: Simplifying Complex System Interfaces" | ||
shortTitle: Session Facade | ||
description: "Learn how to implement the Session Facade Design Pattern in Java to create a unified interface for complex subsystems. Simplify your code and enhance maintainability with practical examples and use cases." | ||
category: Structural | ||
language: en | ||
tag: | ||
- Abstraction | ||
- API design | ||
- Code simplification | ||
- Decoupling | ||
- Encapsulation | ||
- Gang Of Four | ||
- Interface | ||
--- | ||
|
||
## Also known as | ||
|
||
* Session Facade | ||
|
||
## Intent of Session Facade Design Pattern | ||
|
||
Abstracting the underlying business object interactions by providing a service layer that exposes only the required interfaces | ||
|
||
## Detailed Explanation of Session Facade Pattern with Real-World Examples | ||
|
||
Real-world example | ||
|
||
> In an e-commerce website, users interact with several subsystems like product catalogs, shopping carts, | ||
> payment services, and order management. The Session Facade pattern provides a simplified, centralized interface for these subsystems, | ||
> allowing the client to interact with just a few high-level methods (e.g., addToCart(), placeOrder(), selectPaymentMethod()), instead of directly communicating with each subsystem, using a facade supports low coupling between classes and high cohesion within each service, allowing them to focus on their specific responsibilities. | ||
In plain words | ||
|
||
> The Session Facade design pattern is an excellent choice for decoupling complex components of the system that need to be interacting frequently. | ||
## Programmatic Example of Session Facade Pattern in Java | ||
|
||
The Session Facade design pattern is a structural design pattern that provides a simplified interface to a set of complex subsystems, reducing the complexity for the client. This pattern is particularly useful in situations where the client needs to interact with multiple services or systems but doesn’t need to know the internal workings of each service. | ||
|
||
In the context of an e-commerce website, imagine a system where users can browse products, add items to the shopping cart, process payments, and place orders. Instead of the client directly interacting with each individual service (cart, order, payment), the Session Facade provides a single, unified interface for these operations. | ||
|
||
Example Scenario: | ||
In this example, the ShoppingFacade class manages interactions with three subsystems: the `CartService`, `OrderService`, and `PaymentService`. The client interacts with the facade to perform high-level operations like adding items to the cart, placing an order, and selecting a payment method. | ||
|
||
Here’s a simplified programmatic example: | ||
```java | ||
public class App { | ||
public static void main(String[] args) { | ||
ShoppingFacade shoppingFacade = new ShoppingFacade(); | ||
shoppingFacade.addToCart(1); | ||
shoppingFacade.order(); | ||
shoppingFacade.selectPaymentMethod("cash"); | ||
} | ||
} | ||
``` | ||
|
||
The `ShoppingFacade` acts as an intermediary that facilitates interaction between different services promoting low coupling between these services. | ||
```java | ||
public class ShoppingFacade { | ||
|
||
private final CartService cartService; | ||
private final OrderService orderService; | ||
private final PaymentService paymentService; | ||
|
||
public ShoppingFacade() { | ||
Map<Integer, Product> productCatalog = new HashMap<>(); | ||
productCatalog.put(1, new Product(1, "Wireless Mouse", 25.99, "Ergonomic wireless mouse with USB receiver.")); | ||
productCatalog.put(2, new Product(2, "Gaming Keyboard", 79.99, "RGB mechanical gaming keyboard with programmable keys.")); | ||
Map<Integer, Product> cart = new HashMap<>(); | ||
cartService = new CartService(cart, productCatalog); | ||
orderService = new OrderService(cart); | ||
paymentService = new PaymentService(); | ||
} | ||
|
||
public Map<Integer, Product> getCart() { | ||
return this.cartService.getCart(); | ||
} | ||
|
||
public void addToCart(int productId) { | ||
this.cartService.addToCart(productId); | ||
} | ||
|
||
|
||
public void removeFromCart(int productId) { | ||
this.cartService.removeFromCart(productId); | ||
} | ||
|
||
public void order() { | ||
this.orderService.order(); | ||
} | ||
|
||
public Boolean isPaymentRequired() { | ||
double total = this.orderService.getTotal(); | ||
if (total == 0.0) { | ||
LOGGER.info("No payment required"); | ||
return false; | ||
} | ||
return true; | ||
} | ||
|
||
public void processPayment(String method) { | ||
Boolean isPaymentRequired = isPaymentRequired(); | ||
if (Boolean.TRUE.equals(isPaymentRequired)) { | ||
paymentService.selectPaymentMethod(method); | ||
} | ||
} | ||
``` | ||
|
||
Console output for starting the `App` class's `main` method: | ||
``` | ||
19:43:17.883 [main] INFO com.iluwatar.sessionfacade.CartService -- ID: 1 | ||
Name: Wireless Mouse | ||
Price: $25.99 | ||
Description: Ergonomic wireless mouse with USB receiver. successfully added to the cart | ||
19:43:17.910 [main] INFO com.iluwatar.sessionfacade.OrderService -- Client has chosen to order [ID: 1 | ||
``` | ||
This is a basic example of the Session Facade design pattern. The actual implementation would depend on specific requirements of your application. | ||
## When to Use the Session Facade Pattern in Java | ||
* Use when building complex applications with multiple interacting services, where you want to simplify the interaction between various subsystems. | ||
* Ideal for decoupling complex systems that need to interact but should not be tightly coupled. | ||
* Suitable for applications where you need a single point of entry to interact with multiple backend services, like ecommerce platforms, booking systems, or order management systems. | ||
## Real-World Applications of Server Session Pattern in Java | ||
* Enterprise JavaBeans (EJB) | ||
* Java EE (Jakarta EE) Applications | ||
## Benefits and Trade-offs of Server Session Pattern | ||
* Simplifies client-side logic by providing a single entry point for complex operations across multiple services. | ||
* Decouples components of the application, making them easier to maintain, test, and modify without affecting other parts of the system. | ||
* Improves modularity by isolating the implementation details of subsystems from the client. | ||
* Centralizes business logic in one place, making the code easier to manage and update. | ||
## Trade-offs: | ||
* Potential performance bottleneck: Since all requests pass through the facade, it can become a bottleneck if not optimized. | ||
* Increased complexity: If the facade becomes too large or complex, it could counteract the modularity it aims to achieve. | ||
* Single point of failure: If the facade encounters issues, it could affect the entire system's operation, making it crucial to handle errors and exceptions properly. | ||
|
||
## Related Java Design Patterns | ||
|
||
* [Facade](https://java-design-patterns.com/patterns/facade/): The Session Facade pattern is a specific application of the more general Facade pattern, which simplifies access to complex subsystems. | ||
* [Command](https://java-design-patterns.com/patterns/command/): Useful for encapsulating requests and passing them to the session facade, which could then manage the execution order. | ||
* [Singleton](https://java-design-patterns.com/patterns/singleton/): Often used to create a single instance of the session facade for managing the entire workflow of a subsystem. | ||
|
||
## References and Credits | ||
|
||
* [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/4cAbDap) | ||
* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI) | ||
* [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR) |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
@startuml | ||
package com.iluwatar.sessionfacade { | ||
class App { | ||
+ App() | ||
+ main(args : String[]) {static} | ||
} | ||
class CartService { | ||
- LOGGER : Logger {static} | ||
- cart : List<Product> | ||
- productCatalog : List<Product> | ||
+ CartService(cart : List<Product>, productCatalog : List<Product>) | ||
+ addToCart(productId : int) | ||
+ removeFromCart(productId : int) | ||
} | ||
class OrderService { | ||
- LOGGER : Logger {static} | ||
- cart : List<Product> | ||
+ OrderService(cart : List<Product>) | ||
+ order() | ||
} | ||
class PaymentService { | ||
+ LOGGER : Logger {static} | ||
+ PaymentService() | ||
+ cashPayment() | ||
+ creditCardPayment() | ||
+ selectPaymentMethod(method : String) | ||
} | ||
class ProductCatalogService { | ||
- products : List<Product> | ||
+ ProductCatalogService(products : List<Product>) | ||
} | ||
class ShoppingFacade { | ||
~ cart : List<Product> | ||
~ cartService : CartService | ||
~ orderService : OrderService | ||
~ paymentService : PaymentService | ||
~ productCatalog : List<Product> | ||
+ ShoppingFacade() | ||
+ addToCart(productId : int) | ||
+ order() | ||
+ removeFromCart(productId : int) | ||
+ selectPaymentMethod(method : String) | ||
} | ||
} | ||
ShoppingFacade --> "-cartService" CartService | ||
ShoppingFacade --> "-paymentService" PaymentService | ||
ShoppingFacade --> "-orderService" OrderService | ||
@enduml |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
<?xml version="1.0" encoding="UTF-8"?> | ||
<!-- | ||
This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). | ||
The MIT License | ||
Copyright © 2014-2022 Ilkka Seppälä | ||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
The above copyright notice and this permission notice shall be included in | ||
all copies or substantial portions of the Software. | ||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
THE SOFTWARE. | ||
--> | ||
<project xmlns="http://maven.apache.org/POM/4.0.0" | ||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | ||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> | ||
<modelVersion>4.0.0</modelVersion> | ||
<parent> | ||
<groupId>com.iluwatar</groupId> | ||
<artifactId>java-design-patterns</artifactId> | ||
<version>1.26.0-SNAPSHOT</version> | ||
</parent> | ||
|
||
<artifactId>session-facade</artifactId> | ||
<dependencies> | ||
<dependency> | ||
<groupId>org.junit.jupiter</groupId> | ||
<artifactId>junit-jupiter-api</artifactId> | ||
<scope>test</scope> | ||
</dependency> | ||
<dependency> | ||
<groupId>org.mockito</groupId> | ||
<artifactId>mockito-core</artifactId> | ||
<scope>test</scope> | ||
</dependency> | ||
</dependencies> | ||
<build> | ||
<plugins> | ||
<plugin> | ||
<groupId>org.apache.maven.plugins</groupId> | ||
<artifactId>maven-assembly-plugin</artifactId> | ||
<executions> | ||
<execution> | ||
<configuration> | ||
<archive> | ||
<manifest> | ||
<mainClass>com.iluwatar.sessionfacade.App</mainClass> | ||
</manifest> | ||
</archive> | ||
</configuration> | ||
</execution> | ||
</executions> | ||
</plugin> | ||
</plugins> | ||
</build> | ||
</project> |
62 changes: 62 additions & 0 deletions
62
session-facade/src/main/java/com/iluwatar/sessionfacade/App.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
/* | ||
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). | ||
* | ||
* The MIT License | ||
* Copyright © 2014-2022 Ilkka Seppälä | ||
* | ||
* Permission is hereby granted, free of charge, to any person obtaining a copy | ||
* of this software and associated documentation files (the "Software"), to deal | ||
* in the Software without restriction, including without limitation the rights | ||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
* copies of the Software, and to permit persons to whom the Software is | ||
* furnished to do so, subject to the following conditions: | ||
* | ||
* The above copyright notice and this permission notice shall be included in | ||
* all copies or substantial portions of the Software. | ||
* | ||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
* THE SOFTWARE. | ||
*/ | ||
|
||
package com.iluwatar.sessionfacade; | ||
|
||
/** | ||
* The main entry point of the application that demonstrates the usage | ||
* of the ShoppingFacade to manage the shopping process using the Session Facade pattern. | ||
* This class serves as a client that interacts with the simplified | ||
* interface provided by the ShoppingFacade, which encapsulates | ||
* complex interactions with the underlying business services. | ||
* The ShoppingFacade acts as a session bean that coordinates the communication | ||
* between multiple services, hiding their complexity and providing a single, unified API. | ||
*/ | ||
public class App { | ||
/** | ||
* The entry point of the application. | ||
* This method demonstrates how the ShoppingFacade, acting as a Session Facade, is used to: | ||
* - Add items to the shopping cart | ||
* - Process a payment | ||
* - Place the order | ||
* The session facade manages the communication between the individual services | ||
* and simplifies the interactions for the client. | ||
* | ||
* @param args the input arguments | ||
*/ | ||
public static void main(String[] args) { | ||
ShoppingFacade shoppingFacade = new ShoppingFacade(); | ||
|
||
// Adding items to the shopping cart | ||
shoppingFacade.addToCart(1); | ||
shoppingFacade.addToCart(2); | ||
|
||
// Processing the payment with the chosen method | ||
shoppingFacade.processPayment("cash"); | ||
|
||
// Finalizing the order | ||
shoppingFacade.order(); | ||
} | ||
} |
Oops, something went wrong.