简体   繁体   中英

is Proxy class related to proxy design pattern

there is a class in java called Proxy: https://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Proxy.html As I understood it is used to implement interfaces on runtime. On the other side when searching for this, I came across a page explaining the proxy design pattern, so are they related in any way? or they are totally separate things?

A frequent use of the Proxy class is indeed to implement the proxy design pattern in an automated way.

If for example you want to automagically wrap an object inside a proxy with some additional behaviour (let's say rate limiting method calls, but it could really be anything) then Proxy lets you do this in a very general way without writing code that's specific to a given class to proxy.

Note that this is not the only use of the Proxy class however. For example the proxy design pattern is defined in a way that the original object and the proxy have the same interface (ie same methods & so on) and that's not necessary for the Proxy class. The invocation handler doesn't necessary need to forward the calls to a similarly-"shaped" object, but can do whatever it wants. A common example for this is constructing mock objects .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM