我有一个用户通常使用我的工厂创建的对象。我想确保我的用户在将其扔进垃圾收集器之前调用 object.undo() 。
此类设置必要的资源,以便用户不会写入生产服务,而是使用测试特定服务。用户需要调用撤消来恢复其覆盖。
这是我希望用户执行的操作
// in setup()
FooObject object = FooFactory.overrideProductionServicesToTestServices();
// do your testing in test*()
// in tearDown()
object.undo()
这是用户最终所做的事情
// in setup()
FooFactory.overrideProductionServicesToTestServices()
// do their testing. Everything works.
// Another test, everything breaks
如何通过抛出异常或通过类设计来通知用户用户应该调用 undo()?
最佳答案
与其使用终结器(它会影响性能而且很容易出错),为什么不将 PhantomReference
存储到工厂内创建的对象呢?
来自Javadocs :
Phantom references are most often used for scheduling pre-mortem cleanup actions in a more flexible way than is possible with the Java finalization mechanism.
您可以让工厂跟踪该引用的关联 ReferenceQueue
,一旦对象入队,就执行通常由 undo
完成的清理操作。
关于java - 检查在收集对象之前是否调用了方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25655611/