Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
150 changes: 150 additions & 0 deletions gateway/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
---
title: Gateway
category: Structural
language: en
tag:
- Gang of Four
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is not included in the original GoF patterns

- Decoupling

---

## Intent

Provide a interface to access a set of external systems or functionalities. Gateway provides a simple uniform view of
external resources to the internals of an application.

## Explanation

Real-world example

> Gateway acts like a real front gate of a certain city. The people inside the city are called
> internal system, and different outside cities are called external services. The gateway is here
> to provide access for internal system to different external services.

In plain words

> Gateway can provide an interface which lets internal system to utilize external service.

Wikipedia says

> A server that acts as an API front-end, receives API requests, enforces throttling and security
> policies, passes requests to the back-end service and then passes the response back to the requester.

**Programmatic Example**

The main class in our example is the `ExternalService` that contains items.

```java
class ExternalServiceA implements Gateway {
@Override
public void execute() throws Exception {
System.out.println("Executing Service A");
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These should be updated to logger instances

// Simulate a time-consuming task
Thread.sleep(1000);
}
}

/**
* ExternalServiceB is one of external services.
*/
class ExternalServiceB implements Gateway {
@Override
public void execute() throws Exception {
System.out.println("Executing Service B");
// Simulate a time-consuming task
Thread.sleep(1000);
}
}

/**
* ExternalServiceC is one of external services.
*/
class ExternalServiceC implements Gateway {
@Override
public void execute() throws Exception {
System.out.println("Executing Service C");
// Simulate a time-consuming task
Thread.sleep(1000);
}

public void error() throws Exception {
// Simulate an exception
throw new RuntimeException("Service C encountered an error");
}
}
```

To operate these external services, Here's the `App` class:

```java
public class App {
/**
* Simulate an application calling external services.
*/
public static void main(String[] args) throws Exception {
GatewayFactory gatewayFactory = new GatewayFactory();

// Register different gateways
gatewayFactory.registerGateway("ServiceA", new ExternalServiceA());
gatewayFactory.registerGateway("ServiceB", new ExternalServiceB());
gatewayFactory.registerGateway("ServiceC", new ExternalServiceC());

// Use an executor service for asynchronous execution
Gateway serviceA = gatewayFactory.getGateway("ServiceA");
Gateway serviceB = gatewayFactory.getGateway("ServiceB");
Gateway serviceC = gatewayFactory.getGateway("ServiceC");

// Execute external services
try {
serviceA.execute();
serviceB.execute();
serviceC.execute();
} catch (ThreadDeath e) {
System.out.println("Interrupted!" + e);
throw e;
}
}
}
```

The `Gateway` interface is extremely simple.

```java
interface Gateway {
void execute() throws Exception;
}
```

Program output:

```java
Executing Service A
Executing Service B
Executing Service C
```

## Class diagram

![alt text](./etc/gateway.urm.png "gateway")

## Applicability

Use the Gateway pattern

* To access an aggregate object's contents without exposing its internal representation.
* To integration with multiple external services or APIs.
* To provide a uniform interface for traversing different aggregate structures.

## Tutorials

* [Pattern: API Gateway / Backends for Frontends](https://microservices.io/patterns/apigateway.html)

## Known uses

* [API Gateway](https://java-design-patterns.com/patterns/api-gateway/)
* [10 most common use cases of an API Gateway](https://apisix.apache.org/blog/2022/10/27/ten-use-cases-api-gateway/)

## Credits

* [Gateway](https://martinfowler.com/articles/gateway-pattern.html)
* [What is the difference between Facade and Gateway design patterns?](https://stackoverflow.com/questions/4422211/what-is-the-difference-between-facade-and-gateway-design-patterns)
Binary file added gateway/etc/gateway.urm.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
43 changes: 43 additions & 0 deletions gateway/etc/gateway.urm.puml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
@startuml GatewayPattern
package com.iluwatar.gateway{
class App {
+main(args: String[]): void
}

class GatewayFactory {
-gateways: Map<String, Gateway>
+registerGateway(key: String, gateway: Gateway): void
+getGateway(key: String): Gateway
}

interface Gateway {
{abstract} +execute(): void
}

class ExternalServiceA {
+execute(): void
}

class ExternalServiceB {
+execute(): void
}

class ExternalServiceC {
+execute(): void
+error(): void
}

App --> GatewayFactory : Uses


GatewayFactory --> Gateway : Creates

GatewayFactory --> ExternalServiceA : Registers
GatewayFactory --> ExternalServiceB : Registers
GatewayFactory --> ExternalServiceC : Registers

ExternalServiceA --> Gateway : Implements
ExternalServiceB --> Gateway : Implements
ExternalServiceC --> Gateway : Implements

@enduml
68 changes: 68 additions & 0 deletions gateway/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?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>
<packaging>jar</packaging>
<artifactId>gateway</artifactId>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</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.gateway.App</mainClass>
</manifest>
</archive>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
68 changes: 68 additions & 0 deletions gateway/src/main/java/com/iluwatar/gateway/App.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* 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.gateway;

import lombok.extern.slf4j.Slf4j;

/**
* the Gateway design pattern is a structural design pattern that provides a unified interface to a set of
* interfaces in a subsystem. It involves creating a Gateway interface that serves as a common entry point for
* interacting with various services, and concrete implementations of this interface for different external services.
*
* <p>In this example, GateFactory is the factory class, and it provides a method to create different kinds of external
* services. ExternalServiceA, B, and C are virtual implementations of the external services. Each service provides its
* own implementation of the execute() method. The Gateway interface is the common interface for all external services.
* The App class serves as the main entry point for the application implementing the Gateway design pattern. Through
* the Gateway interface, the App class could call each service with much less complexity.
*/
@Slf4j
public class App {
/**
* Simulate an application calling external services.
*/
public static void main(String[] args) throws Exception {
GatewayFactory gatewayFactory = new GatewayFactory();

// Register different gateways
gatewayFactory.registerGateway("ServiceA", new ExternalServiceA());
gatewayFactory.registerGateway("ServiceB", new ExternalServiceB());
gatewayFactory.registerGateway("ServiceC", new ExternalServiceC());

// Use an executor service for execution
Gateway serviceA = gatewayFactory.getGateway("ServiceA");
Gateway serviceB = gatewayFactory.getGateway("ServiceB");
Gateway serviceC = gatewayFactory.getGateway("ServiceC");

// Execute external services
try {
serviceA.execute();
serviceB.execute();
serviceC.execute();
} catch (ThreadDeath e) {
LOGGER.info("Interrupted!" + e);
throw e;
}
}
}
43 changes: 43 additions & 0 deletions gateway/src/main/java/com/iluwatar/gateway/ExternalServiceA.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
* 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.gateway;


import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;

/**
* ExternalServiceA is one of external services.
*/
@Slf4j
class ExternalServiceA implements Gateway {
@Override
public void execute() throws Exception {
LOGGER.info("Executing Service A");
// Simulate a time-consuming task
Thread.sleep(1000);
}
}

Loading