feat: Feature/virtual proxy (#2955)

* feature: Implement Virtual Proxy pattern #2940

* feature: Implement Virtual Proxy pattern #2940

* feature: Implement Virtual Proxy pattern #2940

* feature: Implement Virtual Proxy pattern #2940

* feature: Implement Virtual Proxy pattern #2940

* feature: Implement Virtual Proxy pattern, tests added

* feature: Implement Virtual Proxy pattern, tests added

* feature: Implement Virtual Proxy pattern, tests added

* feature: Implement Virtual Proxy pattern, tests added

* feature: Implement Virtual Proxy pattern, tests added

* feature: Implement Virtual Proxy pattern iluwatar#2940

* feature: Implement Virtual Proxy pattern iluwatar#2940

* refactoring: proxy/pom.xml
This commit is contained in:
Adelya
2024-05-15 09:53:36 +03:00
committed by GitHub
parent 1f7aaef392
commit abbc33295d
13 changed files with 605 additions and 0 deletions
+59
View File
@@ -0,0 +1,59 @@
################## Eclipse ######################
target
.metadata
.settings
.classpath
.project
*.class
tmp/
*.tmp
*.bak
*~.nib
local.properties
.loadpath
.recommenders
.DS_Store
####### Java annotation processor (APT) ########
.factorypath
################ Package Files ##################
*.jar
*.war
*.ear
*.swp
datanucleus.log
/bin/
*.log
event-sourcing/Journal.json
################## Checkstyle ###################
.checkstyle
##################### STS #######################
.apt_generated
.springBeans
.sts4-cache
################# IntelliJ IDEA #################
.idea
*.iws
*.iml
*.ipr
################### NetBeans ####################
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
#################### VS Code ####################
.vscode/
#################### Java Design Patterns #######
etc/Java Design Patterns.urm.puml
serialized-entity/output.txt
+128
View File
@@ -0,0 +1,128 @@
---
title: Virtual Proxy
category: Structural
language: en
tag:
- Gang Of Four
- Decoupling
---
## Also known as
Surrogate
## Intent
Provide a surrogate or placeholder for another object to control its creation and access, particularly when dealing with resource-intensive operations.
## Explanation
Real-world example
> Consider an online video streaming platform where video objects are resource-intensive due to their large data size and required processing power. To efficiently manage resources, the system uses a virtual proxy to handle video objects. The virtual proxy defers the creation of actual video objects until they are explicitly required for playback, thus saving system resources and improving response times for users.
In plain words
> The virtual proxy pattern allows a representative class to stand in for another class to control access to it, particularly for resource-intensive operations.
**Programmatic Example**
Given our example of a video streaming service, here is how it might be implemented:
First, we define an `ExpensiveObject` interface, which outlines the method for processing video.
```java
public interface ExpensiveObject {
void process();
}
```
Heres the implementation of a `RealVideoObject` that represents an expensive-to-create video object.
```java
@Getter
public class RealVideoObject implements ExpensiveObject {
private String videoData;
public RealVideoObject() {
this.videoData = heavyInitialConfiguration();
}
private String heavyInitialConfiguration() {
System.out.println("Loading video data from the database or heavy computation...");
return "Some loaded video data";
}
@Override
public void process() {
System.out.println("Playing video content with data: " + videoData);
}
}
```
The `VideoObjectProxy` serves as a stand-in for `RealExpensiveObject`.
```java
@Getter
public class VideoObjectProxy implements ExpensiveObject {
private RealVideoObject realVideoObject;
public void setRealVideoObject(RealVideoObject realVideoObject) {
this.realVideoObject = realVideoObject;
}
@Override
public void process() {
if (realVideoObject == null) {
System.out.println("RealVideoObject is created on demand.");
realVideoObject = new RealVideoObject();
}
realVideoObject.process();
}
}
```
And heres how the proxy is used in the system.
```
ExpensiveObject object = new VirtualProxy();
object.process(); // The real object is created at this point
object.process(); // Uses the already created object
```
Program output:
```
Creating RealExpensiveObject only when it is needed.
Processing and playing video content...
Processing and playing video content...
```
## Class diagram
![alt text](./etc/virtual.proxy.urm.png "Virtual Proxy pattern class diagram")
## Applicability
The virtual proxy pattern is useful when:
* Object creation is resource-intensive, and not all instances are utilized immediately or ever.
* The performance of a system can be significantly improved by deferring the creation of objects until they are needed.
* There is a need for control over resource usage in systems dealing with large quantities of high-overhead objects.
The virtual proxy pattern is typically used to:
* Lazy Initialization: Create objects only when they are actually needed.
* Resource Management: Efficiently manage resources by creating heavy objects only on demand.
* Access Control: Include logic to check conditions before delegating calls to the actual object.
* Performance Optimization: Incorporate caching of results or states that are expensive to obtain or compute.
* Data Binding and Integration: Delay integration and binding processes until the data is actually needed.
## Related patterns
* [Proxy](https://github.com/iluwatar/java-design-patterns/tree/master/proxy)
## Credits
* [The Proxy Pattern in Java](https://www.baeldung.com/java-proxy-pattern)
* [What is the virtual proxy design pattern?](https://www.educative.io/answers/what-is-the-virtual-proxy-design-pattern)
Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

+29
View File
@@ -0,0 +1,29 @@
@startuml
class Client {
+ main(args : String[]) {static}
}
class RealVideoObject {
- videoData : String
+ RealVideoObject()
+ process()
+ getVideoData() : String
- heavyInitialConfiguration() : void
}
interface ExpensiveObject {
+ process() {abstract}
}
class VideoObjectProxy {
- realVideoObject : RealVideoObject
+ VideoObjectProxy()
+ process()
+ setRealVideoObject(realVideoObject : RealVideoObject) : void
+ getRealVideoObject() : RealVideoObject
}
VideoObjectProxy --> "-realVideoObject" RealVideoObject
RealVideoObject ..|> ExpensiveObject
VideoObjectProxy ..|> ExpensiveObject
@enduml
+73
View File
@@ -0,0 +1,73 @@
<?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>virtual-proxy</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>
<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>App</mainClass>
</manifest>
</archive>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,42 @@
/*
* 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.virtual.proxy;
/**
* The main application class that sets up and runs the Virtual Proxy pattern demo.
*/
public class App {
/**
* The entry point of the application.
*
* @param args the command line arguments
*/
public static void main(String[] args) {
ExpensiveObject videoObject = new VideoObjectProxy();
videoObject.process(); // The first call creates and plays the video
videoObject.process(); // Subsequent call uses the already created object
}
}
@@ -0,0 +1,32 @@
/*
* 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.virtual.proxy;
/**
* Interface for expensive object and proxy object.
*/
public interface ExpensiveObject {
void process();
}
@@ -0,0 +1,50 @@
/*
* 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.virtual.proxy;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
/**
* Represents a real video object that is expensive to create and manage.
*/
@Slf4j
@Getter
public class RealVideoObject implements ExpensiveObject {
public RealVideoObject() {
heavyInitialConfiguration();
}
private void heavyInitialConfiguration() {
LOGGER.info("Loading initial video configurations...");
}
@Override
public void process() {
LOGGER.info("Processing and playing video content...");
}
}
@@ -0,0 +1,44 @@
/*
* 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.virtual.proxy;
import lombok.Getter;
/**
* A proxy class for the real video object, providing a layer of control over the object instantiation.
*/
@Getter
public class VideoObjectProxy implements ExpensiveObject {
private RealVideoObject realVideoObject;
@Override
public void process() {
if (realVideoObject == null) {
realVideoObject = new RealVideoObject();
}
realVideoObject.process();
}
}
@@ -0,0 +1,41 @@
/*
* 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.virtual.proxy;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* Application test
*/
class AppTest {
@Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}
@@ -0,0 +1,53 @@
/*
* 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.virtual.proxy;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import org.junit.jupiter.api.Test;
/**
* Tests for RealVideoObject.
*/
class RealVideoObjectTest {
@Test
void testVideoObject() {
var videoObject = new RealVideoObject();
assertThat(videoObject, instanceOf(ExpensiveObject.class));
}
@Test
public void constructorDoesNotThrowException() {
assertDoesNotThrow(RealVideoObject::new, "Constructor should not throw any exception");
}
@Test
public void processDoesNotThrowException() {
RealVideoObject realVideoObject = new RealVideoObject();
assertDoesNotThrow(realVideoObject::process, "Process method should not throw any exception");
}
}
@@ -0,0 +1,53 @@
/*
* 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.virtual.proxy;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.junit.jupiter.api.Assertions.*;
import org.hamcrest.MatcherAssert;
import org.junit.jupiter.api.Test;
/**
* Tests for VideoObjectProxy.
*/
public class VideoObjectProxyTest {
@Test
void shouldBeInstanceOfExpensiveObject() {
MatcherAssert.assertThat(new VideoObjectProxy(), instanceOf(ExpensiveObject.class));
}
@Test
void constructorDoesNotThrowException() {
assertDoesNotThrow(VideoObjectProxy::new, "Constructor should not throw any exception");
}
@Test
void processDoesNotThrowException() {
assertDoesNotThrow(() -> new VideoObjectProxy().process(), "Process method should not throw any exception");
}
}