Java-处理模式 [英] Java - dispose pattern
问题描述
我想确保正确处置我的对象( Class<?extended Object>
),因为其他实例可能会保存它们使用的数据.例如,用于机密数据的DEK/KEK对.
I want to make sure that my Objects (Class <? extends Object>
) are properly disposed of, because other instances may hold data that are used by them. Example, a DEK/KEK pair for secret data.
由于通常不赞成覆盖 finalize()
,因此如何使IDE警告并强制使开发人员调用 dispose()
是将Object引用设置为null,还是将其自动设置为null(例如退出方法)?
Since Overriding finalize()
is generally frowned upon, how do I make the IDE warn and force the developer to call dispose()
iff the Object reference is set to null, or would be automatically set to null (example exiting a method)?
假定源代码在我的直接控制下,而IDE是Netbeans.
Assuming source code is under my direct control, and the IDE is Netbeans.
推荐答案
首先,值得一提的是,在Java 9中不推荐使用终结器,而推荐使用
First of all, worth to mention that finalizers were deprecated in Java 9 in favour of the Cleaner. Probably this would be the better option then the one I will describe below. Didn't tried it yet though.
谈到问题本身:我会尝试这样做:
Speaking about the question itself: I'd try doing it that way:
- 假设存在一个类型为A的对象,该对象实现了
Closeable
. - 使用唯一的方法制作类S:
void execute(Consumer< A> Consumer)
. - 在方法
execute
中:实例化类型A的对象,将其传递给使用者(accept
),然后将其关闭. - 在客户端代码中-始终使用S,将lambda作为使用者传递给它.在lambda中-您将获得A的实例,而S可以保证将其处置.
- 使所有构造函数对类A的可见性仅限于服务S(例如,使它们成为程序包私有的,并将A与S放在同一程序包中).这样可以防止将A实例化到S之外并使其不受管理.
- Assuming there is an object of type A, which implements
Closeable
. - Make a class S with the only method:
void execute(Consumer<A> consumer)
. - In the method
execute
: instantiate object of type A, pass it to consumer (accept
) then close it. - In the client code - always use S, passing a lambda to it as a consumer. In lambda - you will get the instance of A and S will guarantee disposal of it.
- Make all constructors' visibility of class A limited to only the service S (like, make them package-private and place A in the same package with S). That will prevent A to be instantiated outside of S and left unmanaged.
这篇关于Java-处理模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!