Not able to understand the Proxy cons

2019-09-01 08:20发布

问题:

I was reading about proxy pattern in this article and understood the example, but this commentconfused me. The comment states:

There are 2 big problems with proxies, especially in enterprise environments.

1) You can't do self calls. A good example is a proxy that does transaction management or security. So you need to make sure that instead of doing a self call, you forward the call to the proxy. This makes simple classes complex.

2) There are issues with identity; a good examlpe is a hibernate proxy which makes it impossible to do a reference comparison, even though you get the guarantee that there are not multiple object instances of the same entity in a session.

My questions:

  1. What is the meaning of self call?
  2. Why we can not do a reference comparison when both refers to proxy object?

回答1:

  1. "Self call" refers to calling a method on the same object, using otherMethod() instead of var.otherMethod(). Since the call on the same object goes straight through this and not the proxy, any special treatment that the proxy would apply doesn't happen.

  2. The runtime environment may fiddle around with the proxy object, and you always run the risk of accidentally trying to compare the proxy itself with the business object hiding behind it, as in the case where the object passes a this reference out somewhere and somebody trying to compare it looks it back up from the runtime (and gets the proxy).



标签: java proxy