我觉得应该开File
。
如果您只有一个作为文件工厂的 FileService(每个连接到服务器),您可能希望该服务保持最新。然后你可以使用一些东西:
FactoryServiceImpl implements FactoryService {
public File findFile(criteria) {
return new FileImpl(this);
}
}
// This should be package scope!
FileImpl implements File {
private FactoryService service;
// package scope!
FileImpl(FactoryService service) {
this.service = service;
}
public delete() {
// invalidate this object - all calls should throw exception
// Inform the service that this File should be deleted from
// the server; or if the FileImpl does that itself, that the
// FileService should update the cache of available files
service.delete(this);
}
}
编辑
现在有一个循环依赖,这不是很好。JVM 可能可以检测到它并清理任何东西,但您也可以使用 WeakReference。
无论您使用瘦工厂和事实文件,还是相反,这都是一种设计选择。但是他们需要能够通信,因为通过工厂删除的文件应该知道它已被删除。
一些代码(假设事实工厂):
// This should be package scope!
FileImpl implements File {
private Weakreference<FactoryService> serviceRef;
// package scope!
FileImpl(FactoryService service) {
this.serviceRef = new WeakReference<FactoryService>(service);
}
public delete() {
// invalidate this object - all calls should throw exception
// Inform the service that this File should be deleted from
// the server; or if the FileImpl does that itself, that the
// FileService should update the cache of available files
FactoryService service = serviceRef.get();
if (service != null) {
service.delete(this);
}
}
}
在这种情况下,我假设一个事实工厂,因为可能涉及网络连接,并且在多个对象和线程之间共享连接往往会使关闭该连接的责任不清楚。
这导致 FactoryService 接口应该有一个方法close()
或dispose()
终止连接并使所有文件无效(因为它们不再可访问)。
编辑 2
就 OOD 而言,我可能会尽量模仿 java File API。因此,可以告诉对象删除自己。实现是在 File 中还是在 FileSystem 中的某个地方并不重要(对于接口和类的用户)。