Skip to content

Commit 6b67c0e

Browse files
author
Каспшицкий Алексей
committed
feature: Rate Limiting pattern (iluwatar#2973)
Основа проекта
1 parent d6f2cf2 commit 6b67c0e

File tree

6 files changed

+280
-0
lines changed

6 files changed

+280
-0
lines changed

Diff for: pom.xml

+1
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,7 @@
216216
<module>server-session</module>
217217
<module>virtual-proxy</module>
218218
<module>function-composition</module>
219+
<module>rate-limiting</module>
219220
</modules>
220221
<repositories>
221222
<repository>

Diff for: rate-limiting/README.md

+173
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
---
2+
title: "Proxy Pattern in Java: Enhancing Security and Control with Smart Proxies"
3+
shortTitle: Proxy
4+
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."
5+
category: Structural
6+
language: en
7+
tag:
8+
- Decoupling
9+
- Encapsulation
10+
- Gang Of Four
11+
- Lazy initialization
12+
- Proxy
13+
- Security
14+
- Wrapping
15+
---
16+
17+
## Also known as
18+
19+
* Surrogate
20+
21+
## Intent of Proxy Design Pattern
22+
23+
The Proxy pattern in Java provides a surrogate or placeholder to effectively control access to an object, enhancing security and resource management.
24+
25+
## Detailed Explanation of Proxy Pattern with Real-World Examples
26+
27+
Real-world example
28+
29+
> 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.
30+
31+
In plain words
32+
33+
> Utilizing the Java Proxy pattern, a class encapsulates the functionality of another, streamlining access control and operation efficiency.
34+
35+
Wikipedia says
36+
37+
> 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.
38+
39+
## Programmatic Example of Proxy Pattern in Java
40+
41+
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.
42+
43+
First, we have the `WizardTower` interface and the `IvoryTower` class.
44+
45+
```java
46+
public interface WizardTower {
47+
void enter(Wizard wizard);
48+
}
49+
```
50+
51+
```java
52+
@Slf4j
53+
public class IvoryTower implements WizardTower {
54+
public void enter(Wizard wizard) {
55+
LOGGER.info("{} enters the tower.", wizard);
56+
}
57+
}
58+
```
59+
60+
Then a simple `Wizard` class.
61+
62+
```java
63+
public class Wizard {
64+
65+
private final String name;
66+
67+
public Wizard(String name) {
68+
this.name = name;
69+
}
70+
71+
@Override
72+
public String toString() {
73+
return name;
74+
}
75+
}
76+
```
77+
78+
Then we have the `WizardTowerProxy` to add access control to `WizardTower`.
79+
80+
```java
81+
@Slf4j
82+
public class WizardTowerProxy implements WizardTower {
83+
84+
private static final int NUM_WIZARDS_ALLOWED = 3;
85+
private int numWizards;
86+
private final WizardTower tower;
87+
88+
public WizardTowerProxy(WizardTower tower) {
89+
this.tower = tower;
90+
}
91+
92+
@Override
93+
public void enter(Wizard wizard) {
94+
if (numWizards < NUM_WIZARDS_ALLOWED) {
95+
tower.enter(wizard);
96+
numWizards++;
97+
} else {
98+
LOGGER.info("{} is not allowed to enter!", wizard);
99+
}
100+
}
101+
}
102+
```
103+
104+
And here is the tower entering scenario.
105+
106+
```java
107+
public static void main(String[] args) {
108+
109+
var proxy = new WizardTowerProxy(new IvoryTower());
110+
proxy.enter(new Wizard("Red wizard"));
111+
proxy.enter(new Wizard("White wizard"));
112+
proxy.enter(new Wizard("Black wizard"));
113+
proxy.enter(new Wizard("Green wizard"));
114+
proxy.enter(new Wizard("Brown wizard"));
115+
}
116+
```
117+
118+
Program output:
119+
120+
```
121+
08:42:06.183 [main] INFO com.iluwatar.proxy.IvoryTower -- Red wizard enters the tower.
122+
08:42:06.186 [main] INFO com.iluwatar.proxy.IvoryTower -- White wizard enters the tower.
123+
08:42:06.186 [main] INFO com.iluwatar.proxy.IvoryTower -- Black wizard enters the tower.
124+
08:42:06.186 [main] INFO com.iluwatar.proxy.WizardTowerProxy -- Green wizard is not allowed to enter!
125+
08:42:06.186 [main] INFO com.iluwatar.proxy.WizardTowerProxy -- Brown wizard is not allowed to enter!
126+
```
127+
128+
## When to Use the Proxy Pattern in Java
129+
130+
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
131+
132+
* Control access to another object
133+
* Lazy initialization
134+
* Implement logging
135+
* Facilitate network connection
136+
* Count references to an object
137+
* Provide a local representation for an object that is in a different address space.
138+
139+
## Real-World Applications of Proxy Pattern in Java
140+
141+
* 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.
142+
* Remote Proxies: Used in remote method invocation (RMI) to manage interactions with remote objects.
143+
* Protection Proxies: Control access to the original object to ensure proper authorization.
144+
* [java.lang.reflect.Proxy](http://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Proxy.html)
145+
* [Apache Commons Proxy](https://commons.apache.org/proper/commons-proxy/)
146+
* Mocking frameworks [Mockito](https://site.mockito.org/),[Powermock](https://powermock.github.io/), [EasyMock](https://easymock.org/)
147+
* [UIAppearance](https://developer.apple.com/documentation/uikit/uiappearance)
148+
149+
## Benefits and Trade-offs of Proxy Pattern
150+
151+
Benefits:
152+
153+
* Controlled Access: Proxies control access to the real object, allowing for checks, logging, or other operations.
154+
* Lazy Initialization: Proxies can delay the creation and initialization of resource-intensive objects until they are needed.
155+
* Remote Proxy Handling: Simplifies interaction with remote objects by handling the network communication.
156+
157+
Trade-offs:
158+
159+
* Overhead: Adding a proxy introduces additional layers that might add overhead.
160+
* Complexity: Increases the complexity of the system by adding more classes.
161+
162+
## Related Java Design Patterns
163+
164+
* [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.
165+
* [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.
166+
* [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.
167+
* [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.
168+
169+
## References and Credits
170+
171+
* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0pvKI)
172+
* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/49NGldq)
173+
* [Java Design Patterns: A Hands-On Experience with Real-World Examples](https://amzn.to/3yhh525)

Diff for: rate-limiting/etc/proxy.urm.png

28.1 KB
Loading

Diff for: rate-limiting/etc/proxy.urm.puml

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
@startuml
2+
package com.iluwatar.proxy {
3+
class App {
4+
+ App()
5+
+ main(args : String[]) {static}
6+
}
7+
class IvoryTower {
8+
- LOGGER : Logger {static}
9+
+ IvoryTower()
10+
+ enter(wizard : Wizard)
11+
}
12+
class Wizard {
13+
- name : String
14+
+ Wizard(name : String)
15+
+ toString() : String
16+
}
17+
interface WizardTower {
18+
+ enter(Wizard) {abstract}
19+
}
20+
class WizardTowerProxy {
21+
- LOGGER : Logger {static}
22+
- NUM_WIZARDS_ALLOWED : int {static}
23+
- numWizards : int
24+
- tower : WizardTower
25+
+ WizardTowerProxy(tower : WizardTower)
26+
+ enter(wizard : Wizard)
27+
}
28+
}
29+
WizardTowerProxy --> "-tower" WizardTower
30+
IvoryTower ..|> WizardTower
31+
WizardTowerProxy ..|> WizardTower
32+
@enduml

Diff for: rate-limiting/pom.xml

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
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" 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">
29+
<modelVersion>4.0.0</modelVersion>
30+
<parent>
31+
<groupId>com.iluwatar</groupId>
32+
<artifactId>java-design-patterns</artifactId>
33+
<version>1.26.0-SNAPSHOT</version>
34+
</parent>
35+
<artifactId>rate-limiting</artifactId>
36+
<dependencies>
37+
<dependency>
38+
<groupId>org.junit.jupiter</groupId>
39+
<artifactId>junit-jupiter-engine</artifactId>
40+
<scope>test</scope>
41+
</dependency>
42+
<dependency>
43+
<groupId>org.mockito</groupId>
44+
<artifactId>mockito-core</artifactId>
45+
<scope>test</scope>
46+
</dependency>
47+
</dependencies>
48+
<build>
49+
<plugins>
50+
<plugin>
51+
<groupId>org.apache.maven.plugins</groupId>
52+
<artifactId>maven-assembly-plugin</artifactId>
53+
<executions>
54+
<execution>
55+
<configuration>
56+
<archive>
57+
<manifest>
58+
<mainClass>com.iluwatar.proxy.App</mainClass>
59+
</manifest>
60+
</archive>
61+
</configuration>
62+
</execution>
63+
</executions>
64+
</plugin>
65+
</plugins>
66+
</build>
67+
</project>

Diff for: rate-limiting/src/main/java/com/iluwatar/Main.java

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package com.iluwatar;
2+
3+
public class Main {
4+
public static void main(String[] args) {
5+
System.out.println("Hello world!");
6+
}
7+
}

0 commit comments

Comments
 (0)