Skip to content

Commit 8cb7c9a

Browse files
shahdhossiluwatar
andauthored
feat: Implementation of session facade design pattern iluwatar#1278 (iluwatar#3121)
* implementation of session facade iluwatar#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]>
1 parent bcad5b1 commit 8cb7c9a

File tree

17 files changed

+1180
-0
lines changed

17 files changed

+1180
-0
lines changed

pom.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,7 @@
219219
<module>microservices-distributed-tracing</module>
220220
<module>microservices-client-side-ui-composition</module>
221221
<module>microservices-idempotent-consumer</module>
222+
<module>session-facade</module>
222223
<module>templateview</module>
223224
<module>money</module>
224225
<module>table-inheritance</module>

session-facade/README.md

Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
---
2+
title: "Session Facade Pattern in Java: Simplifying Complex System Interfaces"
3+
shortTitle: Session Facade
4+
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."
5+
category: Structural
6+
language: en
7+
tag:
8+
- Abstraction
9+
- API design
10+
- Code simplification
11+
- Decoupling
12+
- Encapsulation
13+
- Gang Of Four
14+
- Interface
15+
---
16+
17+
## Also known as
18+
19+
* Session Facade
20+
21+
## Intent of Session Facade Design Pattern
22+
23+
Abstracting the underlying business object interactions by providing a service layer that exposes only the required interfaces
24+
25+
## Detailed Explanation of Session Facade Pattern with Real-World Examples
26+
27+
Real-world example
28+
29+
> In an e-commerce website, users interact with several subsystems like product catalogs, shopping carts,
30+
> payment services, and order management. The Session Facade pattern provides a simplified, centralized interface for these subsystems,
31+
> 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.
32+
33+
In plain words
34+
35+
> The Session Facade design pattern is an excellent choice for decoupling complex components of the system that need to be interacting frequently.
36+
37+
## Programmatic Example of Session Facade Pattern in Java
38+
39+
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.
40+
41+
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.
42+
43+
Example Scenario:
44+
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.
45+
46+
Here’s a simplified programmatic example:
47+
```java
48+
public class App {
49+
public static void main(String[] args) {
50+
ShoppingFacade shoppingFacade = new ShoppingFacade();
51+
shoppingFacade.addToCart(1);
52+
shoppingFacade.order();
53+
shoppingFacade.selectPaymentMethod("cash");
54+
}
55+
}
56+
```
57+
58+
The `ShoppingFacade` acts as an intermediary that facilitates interaction between different services promoting low coupling between these services.
59+
```java
60+
public class ShoppingFacade {
61+
62+
private final CartService cartService;
63+
private final OrderService orderService;
64+
private final PaymentService paymentService;
65+
66+
public ShoppingFacade() {
67+
Map<Integer, Product> productCatalog = new HashMap<>();
68+
productCatalog.put(1, new Product(1, "Wireless Mouse", 25.99, "Ergonomic wireless mouse with USB receiver."));
69+
productCatalog.put(2, new Product(2, "Gaming Keyboard", 79.99, "RGB mechanical gaming keyboard with programmable keys."));
70+
Map<Integer, Product> cart = new HashMap<>();
71+
cartService = new CartService(cart, productCatalog);
72+
orderService = new OrderService(cart);
73+
paymentService = new PaymentService();
74+
}
75+
76+
public Map<Integer, Product> getCart() {
77+
return this.cartService.getCart();
78+
}
79+
80+
public void addToCart(int productId) {
81+
this.cartService.addToCart(productId);
82+
}
83+
84+
85+
public void removeFromCart(int productId) {
86+
this.cartService.removeFromCart(productId);
87+
}
88+
89+
public void order() {
90+
this.orderService.order();
91+
}
92+
93+
public Boolean isPaymentRequired() {
94+
double total = this.orderService.getTotal();
95+
if (total == 0.0) {
96+
LOGGER.info("No payment required");
97+
return false;
98+
}
99+
return true;
100+
}
101+
102+
public void processPayment(String method) {
103+
Boolean isPaymentRequired = isPaymentRequired();
104+
if (Boolean.TRUE.equals(isPaymentRequired)) {
105+
paymentService.selectPaymentMethod(method);
106+
}
107+
}
108+
```
109+
110+
Console output for starting the `App` class's `main` method:
111+
112+
```
113+
19:43:17.883 [main] INFO com.iluwatar.sessionfacade.CartService -- ID: 1
114+
Name: Wireless Mouse
115+
Price: $25.99
116+
Description: Ergonomic wireless mouse with USB receiver. successfully added to the cart
117+
19:43:17.910 [main] INFO com.iluwatar.sessionfacade.OrderService -- Client has chosen to order [ID: 1
118+
```
119+
120+
This is a basic example of the Session Facade design pattern. The actual implementation would depend on specific requirements of your application.
121+
122+
## When to Use the Session Facade Pattern in Java
123+
124+
* Use when building complex applications with multiple interacting services, where you want to simplify the interaction between various subsystems.
125+
* Ideal for decoupling complex systems that need to interact but should not be tightly coupled.
126+
* 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.
127+
128+
## Real-World Applications of Server Session Pattern in Java
129+
130+
* Enterprise JavaBeans (EJB)
131+
* Java EE (Jakarta EE) Applications
132+
133+
## Benefits and Trade-offs of Server Session Pattern
134+
135+
136+
* Simplifies client-side logic by providing a single entry point for complex operations across multiple services.
137+
* Decouples components of the application, making them easier to maintain, test, and modify without affecting other parts of the system.
138+
* Improves modularity by isolating the implementation details of subsystems from the client.
139+
* Centralizes business logic in one place, making the code easier to manage and update.
140+
141+
## Trade-offs:
142+
143+
* Potential performance bottleneck: Since all requests pass through the facade, it can become a bottleneck if not optimized.
144+
* Increased complexity: If the facade becomes too large or complex, it could counteract the modularity it aims to achieve.
145+
* 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.
146+
147+
## Related Java Design Patterns
148+
149+
* [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.
150+
* [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.
151+
* [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.
152+
153+
## References and Credits
154+
155+
* [Core J2EE Patterns: Best Practices and Design Strategies](https://amzn.to/4cAbDap)
156+
* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
157+
* [Patterns of Enterprise Application Architecture](https://amzn.to/3WfKBPR)
92.6 KB
Loading
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
@startuml
2+
package com.iluwatar.sessionfacade {
3+
class App {
4+
+ App()
5+
+ main(args : String[]) {static}
6+
}
7+
class CartService {
8+
- LOGGER : Logger {static}
9+
- cart : List<Product>
10+
- productCatalog : List<Product>
11+
+ CartService(cart : List<Product>, productCatalog : List<Product>)
12+
+ addToCart(productId : int)
13+
+ removeFromCart(productId : int)
14+
}
15+
class OrderService {
16+
- LOGGER : Logger {static}
17+
- cart : List<Product>
18+
+ OrderService(cart : List<Product>)
19+
+ order()
20+
}
21+
class PaymentService {
22+
+ LOGGER : Logger {static}
23+
+ PaymentService()
24+
+ cashPayment()
25+
+ creditCardPayment()
26+
+ selectPaymentMethod(method : String)
27+
}
28+
class ProductCatalogService {
29+
- products : List<Product>
30+
+ ProductCatalogService(products : List<Product>)
31+
}
32+
class ShoppingFacade {
33+
~ cart : List<Product>
34+
~ cartService : CartService
35+
~ orderService : OrderService
36+
~ paymentService : PaymentService
37+
~ productCatalog : List<Product>
38+
+ ShoppingFacade()
39+
+ addToCart(productId : int)
40+
+ order()
41+
+ removeFromCart(productId : int)
42+
+ selectPaymentMethod(method : String)
43+
}
44+
}
45+
ShoppingFacade --> "-cartService" CartService
46+
ShoppingFacade --> "-paymentService" PaymentService
47+
ShoppingFacade --> "-orderService" OrderService
48+
@enduml

session-facade/pom.xml

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!--
3+
4+
This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
5+
6+
The MIT License
7+
Copyright © 2014-2022 Ilkka Seppälä
8+
9+
Permission is hereby granted, free of charge, to any person obtaining a copy
10+
of this software and associated documentation files (the "Software"), to deal
11+
in the Software without restriction, including without limitation the rights
12+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13+
copies of the Software, and to permit persons to whom the Software is
14+
furnished to do so, subject to the following conditions:
15+
16+
The above copyright notice and this permission notice shall be included in
17+
all copies or substantial portions of the Software.
18+
19+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25+
THE SOFTWARE.
26+
27+
-->
28+
<project xmlns="http://maven.apache.org/POM/4.0.0"
29+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
30+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
31+
<modelVersion>4.0.0</modelVersion>
32+
<parent>
33+
<groupId>com.iluwatar</groupId>
34+
<artifactId>java-design-patterns</artifactId>
35+
<version>1.26.0-SNAPSHOT</version>
36+
</parent>
37+
38+
<artifactId>session-facade</artifactId>
39+
<dependencies>
40+
<dependency>
41+
<groupId>org.junit.jupiter</groupId>
42+
<artifactId>junit-jupiter-api</artifactId>
43+
<scope>test</scope>
44+
</dependency>
45+
<dependency>
46+
<groupId>org.mockito</groupId>
47+
<artifactId>mockito-core</artifactId>
48+
<scope>test</scope>
49+
</dependency>
50+
</dependencies>
51+
<build>
52+
<plugins>
53+
<plugin>
54+
<groupId>org.apache.maven.plugins</groupId>
55+
<artifactId>maven-assembly-plugin</artifactId>
56+
<executions>
57+
<execution>
58+
<configuration>
59+
<archive>
60+
<manifest>
61+
<mainClass>com.iluwatar.sessionfacade.App</mainClass>
62+
</manifest>
63+
</archive>
64+
</configuration>
65+
</execution>
66+
</executions>
67+
</plugin>
68+
</plugins>
69+
</build>
70+
</project>
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/*
2+
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
3+
*
4+
* The MIT License
5+
* Copyright © 2014-2022 Ilkka Seppälä
6+
*
7+
* Permission is hereby granted, free of charge, to any person obtaining a copy
8+
* of this software and associated documentation files (the "Software"), to deal
9+
* in the Software without restriction, including without limitation the rights
10+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11+
* copies of the Software, and to permit persons to whom the Software is
12+
* furnished to do so, subject to the following conditions:
13+
*
14+
* The above copyright notice and this permission notice shall be included in
15+
* all copies or substantial portions of the Software.
16+
*
17+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23+
* THE SOFTWARE.
24+
*/
25+
26+
package com.iluwatar.sessionfacade;
27+
28+
/**
29+
* The main entry point of the application that demonstrates the usage
30+
* of the ShoppingFacade to manage the shopping process using the Session Facade pattern.
31+
* This class serves as a client that interacts with the simplified
32+
* interface provided by the ShoppingFacade, which encapsulates
33+
* complex interactions with the underlying business services.
34+
* The ShoppingFacade acts as a session bean that coordinates the communication
35+
* between multiple services, hiding their complexity and providing a single, unified API.
36+
*/
37+
public class App {
38+
/**
39+
* The entry point of the application.
40+
* This method demonstrates how the ShoppingFacade, acting as a Session Facade, is used to:
41+
* - Add items to the shopping cart
42+
* - Process a payment
43+
* - Place the order
44+
* The session facade manages the communication between the individual services
45+
* and simplifies the interactions for the client.
46+
*
47+
* @param args the input arguments
48+
*/
49+
public static void main(String[] args) {
50+
ShoppingFacade shoppingFacade = new ShoppingFacade();
51+
52+
// Adding items to the shopping cart
53+
shoppingFacade.addToCart(1);
54+
shoppingFacade.addToCart(2);
55+
56+
// Processing the payment with the chosen method
57+
shoppingFacade.processPayment("cash");
58+
59+
// Finalizing the order
60+
shoppingFacade.order();
61+
}
62+
}

0 commit comments

Comments
 (0)