Java-处理模式 [英] Java - dispose pattern

查看:81
本文介绍了Java-处理模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想确保正确处置我的对象( 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:

  1. 假设存在一个类型为A的对象,该对象实现了 Closeable .
  2. 使用唯一的方法制作类S: void execute(Consumer< A> Consumer).
  3. 在方法 execute 中:实例化类型A的对象,将其传递给使用者( accept ),然后将其关闭.
  4. 在客户端代码中-始终使用S,将lambda作为使用者传递给它.在lambda中-您将获得A的实例,而S可以保证将其处置.
  5. 使所有构造函数对类A的可见性仅限于服务S(例如,使它们成为程序包私有的,并将A与S放在同一程序包中).这样可以防止将A实例化到S之外并使其不受管理.
  1. Assuming there is an object of type A, which implements Closeable.
  2. Make a class S with the only method: void execute(Consumer<A> consumer).
  3. In the method execute: instantiate object of type A, pass it to consumer (accept) then close it.
  4. 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.
  5. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆