Skip to content

Commit

Permalink
feature: Rate Limiting pattern (iluwatar#2973)
Browse files Browse the repository at this point in the history
Основа проекта
  • Loading branch information
Каспшицкий Алексей committed Jul 4, 2024
1 parent d6f2cf2 commit 6b67c0e
Show file tree
Hide file tree
Showing 6 changed files with 280 additions and 0 deletions.
1 change: 1 addition & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,7 @@
<module>server-session</module>
<module>virtual-proxy</module>
<module>function-composition</module>
<module>rate-limiting</module>
</modules>
<repositories>
<repository>
Expand Down
173 changes: 173 additions & 0 deletions rate-limiting/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
---
title: "Proxy Pattern in Java: Enhancing Security and Control with Smart Proxies"
shortTitle: Proxy
description: "Explore the Proxy design pattern in Java with detailed examples. Learn how it provides controlled access, facilitates lazy initialization, and ensures security. Ideal for developers looking to implement advanced Java techniques."
category: Structural
language: en
tag:
- Decoupling
- Encapsulation
- Gang Of Four
- Lazy initialization
- Proxy
- Security
- Wrapping
---

## Also known as

* Surrogate

## Intent of Proxy Design Pattern

The Proxy pattern in Java provides a surrogate or placeholder to effectively control access to an object, enhancing security and resource management.

## Detailed Explanation of Proxy Pattern with Real-World Examples

Real-world example

> In a real-world scenario, consider a security guard at a gated community. The security guard acts as a proxy for the residents. When a visitor arrives, the guard checks the visitor's credentials and permissions before allowing them access to the community. If the visitor is authorized, the guard grants entry; if not, entry is denied. This ensures that only authorized individuals can access the community, much like a Proxy design pattern controls access to a specific object.
In plain words

> Utilizing the Java Proxy pattern, a class encapsulates the functionality of another, streamlining access control and operation efficiency.
Wikipedia says

> A proxy, in its most general form, is a class functioning as an interface to something else. A proxy is a wrapper or agent object that is being called by the client to access the real serving object behind the scenes. Use of the proxy can simply be forwarding to the real object, or can provide additional logic. In the proxy extra functionality can be provided, for example caching when operations on the real object are resource intensive, or checking preconditions before operations on the real object are invoked.
## Programmatic Example of Proxy Pattern in Java

Imagine a tower where the local wizards go to study their spells. The ivory tower can only be accessed through a proxy which ensures that only the first three wizards can enter. Here the proxy represents the functionality of the tower and adds access control to it.

First, we have the `WizardTower` interface and the `IvoryTower` class.

```java
public interface WizardTower {
void enter(Wizard wizard);
}
```

```java
@Slf4j
public class IvoryTower implements WizardTower {
public void enter(Wizard wizard) {
LOGGER.info("{} enters the tower.", wizard);
}
}
```

Then a simple `Wizard` class.

```java
public class Wizard {

private final String name;

public Wizard(String name) {
this.name = name;
}

@Override
public String toString() {
return name;
}
}
```

Then we have the `WizardTowerProxy` to add access control to `WizardTower`.

```java
@Slf4j
public class WizardTowerProxy implements WizardTower {

private static final int NUM_WIZARDS_ALLOWED = 3;
private int numWizards;
private final WizardTower tower;

public WizardTowerProxy(WizardTower tower) {
this.tower = tower;
}

@Override
public void enter(Wizard wizard) {
if (numWizards < NUM_WIZARDS_ALLOWED) {
tower.enter(wizard);
numWizards++;
} else {
LOGGER.info("{} is not allowed to enter!", wizard);
}
}
}
```

And here is the tower entering scenario.

```java
public static void main(String[] args) {

var proxy = new WizardTowerProxy(new IvoryTower());
proxy.enter(new Wizard("Red wizard"));
proxy.enter(new Wizard("White wizard"));
proxy.enter(new Wizard("Black wizard"));
proxy.enter(new Wizard("Green wizard"));
proxy.enter(new Wizard("Brown wizard"));
}
```

Program output:

```
08:42:06.183 [main] INFO com.iluwatar.proxy.IvoryTower -- Red wizard enters the tower.
08:42:06.186 [main] INFO com.iluwatar.proxy.IvoryTower -- White wizard enters the tower.
08:42:06.186 [main] INFO com.iluwatar.proxy.IvoryTower -- Black wizard enters the tower.
08:42:06.186 [main] INFO com.iluwatar.proxy.WizardTowerProxy -- Green wizard is not allowed to enter!
08:42:06.186 [main] INFO com.iluwatar.proxy.WizardTowerProxy -- Brown wizard is not allowed to enter!
```

## When to Use the Proxy Pattern in Java

Proxy is applicable whenever there is a need for a more versatile or sophisticated reference to an object than a simple pointer. Here are several common situations in which the Proxy pattern is applicable. Typically, the proxy pattern is used to

* Control access to another object
* Lazy initialization
* Implement logging
* Facilitate network connection
* Count references to an object
* Provide a local representation for an object that is in a different address space.

## Real-World Applications of Proxy Pattern in Java

* Virtual Proxies: In applications that need heavy resources like large images or complex calculations, virtual proxies can be used to instantiate objects only when needed.
* Remote Proxies: Used in remote method invocation (RMI) to manage interactions with remote objects.
* Protection Proxies: Control access to the original object to ensure proper authorization.
* [java.lang.reflect.Proxy](http://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Proxy.html)
* [Apache Commons Proxy](https://commons.apache.org/proper/commons-proxy/)
* Mocking frameworks [Mockito](https://site.mockito.org/),[Powermock](https://powermock.github.io/), [EasyMock](https://easymock.org/)
* [UIAppearance](https://developer.apple.com/documentation/uikit/uiappearance)

## Benefits and Trade-offs of Proxy Pattern

Benefits:

* Controlled Access: Proxies control access to the real object, allowing for checks, logging, or other operations.
* Lazy Initialization: Proxies can delay the creation and initialization of resource-intensive objects until they are needed.
* Remote Proxy Handling: Simplifies interaction with remote objects by handling the network communication.

Trade-offs:

* Overhead: Adding a proxy introduces additional layers that might add overhead.
* Complexity: Increases the complexity of the system by adding more classes.

## Related Java Design Patterns

* [Adapter](https://java-design-patterns.com/patterns/adapter/): The Adapter pattern changes the interface of an existing object, whereas Proxy provides the same interface as the original object.
* [Ambassador](https://java-design-patterns.com/patterns/ambassador/): Ambassador is similar to Proxy as it acts as an intermediary, especially in remote communications, enhancing access control and monitoring.
* [Decorator](https://java-design-patterns.com/patterns/decorator/): Both Decorator and Proxy patterns provide a level of indirection, but the Decorator pattern adds responsibilities to objects dynamically, while Proxy controls access.
* [Facade](https://java-design-patterns.com/patterns/facade/): Facade provides a simplified interface to a complex subsystem, while Proxy controls access to a particular object.

## References and Credits

* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)
* [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525)
Binary file added rate-limiting/etc/proxy.urm.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
32 changes: 32 additions & 0 deletions rate-limiting/etc/proxy.urm.puml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
@startuml
package com.iluwatar.proxy {
class App {
+ App()
+ main(args : String[]) {static}
}
class IvoryTower {
- LOGGER : Logger {static}
+ IvoryTower()
+ enter(wizard : Wizard)
}
class Wizard {
- name : String
+ Wizard(name : String)
+ toString() : String
}
interface WizardTower {
+ enter(Wizard) {abstract}
}
class WizardTowerProxy {
- LOGGER : Logger {static}
- NUM_WIZARDS_ALLOWED : int {static}
- numWizards : int
- tower : WizardTower
+ WizardTowerProxy(tower : WizardTower)
+ enter(wizard : Wizard)
}
}
WizardTowerProxy --> "-tower" WizardTower
IvoryTower ..|> WizardTower
WizardTowerProxy ..|> WizardTower
@enduml
67 changes: 67 additions & 0 deletions rate-limiting/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?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>rate-limiting</artifactId>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</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.proxy.App</mainClass>
</manifest>
</archive>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
7 changes: 7 additions & 0 deletions rate-limiting/src/main/java/com/iluwatar/Main.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.iluwatar;

public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}

0 comments on commit 6b67c0e

Please sign in to comment.