gpt4 book ai didi

java - 什么时候使用 "Dynamic Proxy class"或 "standard proxy"模式?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:55:02 25 4
gpt4 key购买 nike

为什么要使用“动态代理类”而不是“标准代理”模式?

两者的优缺点是什么?

看起来它们都有相同的最终结果,只是它们的实现方式不同。

动态代理类 https://docs.oracle.com/javase/8/docs/technotes/guides/reflection/proxy.html

A dynamic proxy class is a class that implements a list of interfaces specified at runtime such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface. Thus, a dynamic proxy class can be used to create a type-safe proxy object for a list of interfaces without requiring pre-generation of the proxy class, such as with compile-time tools. Method invocations on an instance of a dynamic proxy class are dispatched to a single method in the instance's invocation handler, and they are encoded with a java.lang.reflect.Method object identifying the method that was invoked and an array of type Object containing the arguments.

标准代理模式 https://en.wikipedia.org/wiki/Proxy_pattern

A proxy, in its most general form, is a class functioning as an interface to something else. The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate. In short, a proxy is a wrapper or agent object that is being called by the client to access the real serving object behind the scenes. In the proxy extra functionality can be provided, for example caching when operations on the real object are resource intensive, or checking preconditions before operations on the real object are invoked. For the client, usage of a proxy object is similar to using the real object, because both implement the same interface.

最佳答案

您似乎回答了自己的问题。您应该使用更容易为您的用例实现的那个。

当你在编译时没有每个方法的实现时,你需要动态代理。

例如,模拟测试库使用动态代理,以便可以编写代码来通用地处理任何方法。

关于java - 什么时候使用 "Dynamic Proxy class"或 "standard proxy"模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35279850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com