Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

differences between proxy and dynamic proxy patterns

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)

like image 877
Shai Zarzewski Avatar asked Dec 14 '13 14:12

Shai Zarzewski


1 Answers

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:

  1. Create proxy class for each class.
  2. implement proxy class in a way, that first it make a log entry of the method call made by the client, than delegate the call to real object.

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:

  1. client call some action on an object.
  2. system create a proxy object at runtime based on client's call.
  3. proxy object calls a generic method to perform a generic action in case of each call.
  4. after the action, proxy object delegate the call to real object.

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.

like image 121
Ugrasen Banchhor Avatar answered Sep 28 '22 05:09

Ugrasen Banchhor