I'm trying to understand what are the differences between proxy and dynamic proxy patterns. from what I've read so far the only thing that I found out is that the proxy class byte-code is created during compile time and on dynamic proxy it's created during run-time. are there another differences that i'm missing? if not then what's the reason to prefer proxy over dynamic proxy (except performance issues)
Dynamic proxy is essentially the proxy design pattern, in which the proxy object is created dynamically during runtime.
Proxy design pattern uses a proxy, which acts as a mediator between client and underlying real object. Programmer can perform access control, validation and additional action in proxy before delegating the request to real object.
Now suppose you want to perform some generic action before calling any method of any class for example you want to keep log of all the method calls made by client. In that case, if you want to implement proxy design pattern, steps are as following:
the problem with above technique is that, suppose you have 1000 classes, you'll need to write 1000 proxy classes for each class and implements all the method in all the classes which essentially doing the same thing(performing logging action in our case), which is very tedious process and wastage of memory.
Won't it be better, if somehow at runtime, we are able to create a proxy object based on the client's call and then perform generic action(logging action in our case) before delegating the call to the real object, well that what dyanmic proxies does.
The process in case of dyanamic proxy is as following:
so in a nutshell, if you have some generic action to perform, use dynamic proxy, but if you want each class to be treated differenlty (in some class perform logging, in some don't, in some access contorl etc.) use simple proxy. Hope I helped. If you need a code example, please let me know.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With