我有以下内容:

interface File
{
  String name();
  ...
}

interface FileService
{
  List<File> getAllFiles();
  ...
}


使用此类接口时,如果我决定删除以File实例表示的实体(我的意思是从远程服务器中删除),该怎么办?

我应该为文件接口引入delete()方法吗(因为它是Information Expert,并且可能知道如何从服务器中删除自身)?还是应该通过FileService接口方法将此函数委托给它的创建者-void deleteFile(File file)?又为什么呢?

如果第一种情况更合适,如何使对象无效以避免其后续使用?

和相关:我应该如何处理uploadFile()案件?谁应该对此负责?因为似乎FileService可能会违反SRP。

谢谢,

最佳答案

我认为应该在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中的某个位置并不重要(对于接口和类的用户)。

10-07 13:20
查看更多