Proxy is a very popular pattern used in Java. It is like a wrapper around an object. When a method on the proxy object is invoked, it will decide if method on original object will be invoked or some handle. Handler may invoke method on original method with some additional logic.
Most popular usages of proxy pattern:
- Emitting metrics when a method starts or stops.
- Adding some additional logging around method invocation.
- Mocking behavior of original class.
When I had to create a proxy object for a java class (instead of interface), I was able to find lot of example codes for creating a proxy for interface on internet. But I had a difficult time finding code snippets for class and piecing it together. This motivated me to share my example code. I could have had much simpler example but decided otherwise. This gives insight about how to handle complex objects and there is nothing simple in the wild anyway.
In this example, our goal is to count how many times method getFirst() of BoxPair is called.
BoxPair is a simple class build on top of Box class.
RandomInvoker takes a boxPair object and calls getFirst() or getSecond() randomly.
To count how many times getFirst() is called inside RandomInvoker.run(), lets create a proxy object around boxPair object which takes a counter to count getFirst() method invocations.
Here is the final piece to glue it altogether.
GitHub repo for code mentioned above: https://github.com/ajitak/java-proxy
Most popular usages of proxy pattern:
- Emitting metrics when a method starts or stops.
- Adding some additional logging around method invocation.
- Mocking behavior of original class.
When I had to create a proxy object for a java class (instead of interface), I was able to find lot of example codes for creating a proxy for interface on internet. But I had a difficult time finding code snippets for class and piecing it together. This motivated me to share my example code. I could have had much simpler example but decided otherwise. This gives insight about how to handle complex objects and there is nothing simple in the wild anyway.
In this example, our goal is to count how many times method getFirst() of BoxPair is called.
BoxPair is a simple class build on top of Box class.
RandomInvoker takes a boxPair object and calls getFirst() or getSecond() randomly.
To count how many times getFirst() is called inside RandomInvoker.run(), lets create a proxy object around boxPair object which takes a counter to count getFirst() method invocations.
Here is the final piece to glue it altogether.
GitHub repo for code mentioned above: https://github.com/ajitak/java-proxy
1 comment:
Great job for publishing such a nice article. Your article isn’t only useful but it is additionally really informative. Thank you because you have been willing to share information with us.Data structures and algorithms course
Post a Comment