【问题标题】:Defining the correct association relation between classes定义类之间正确的关联关系
【发布时间】:2012-03-21 00:33:00
【问题描述】:

在我目前正在开发的一个模块中,我尝试将需求建模为具有正确关系的类图。

要求:

  1. 该模块将连接到一组 ftp 服务器并下载一些文件。
  2. 该模块将解析每个文件以生成一组发票。

所以我创建了 4 个类 File、Ftp 和 Parser。现在我想我应该让 File 类能够download()parse() 本身。

class File{    
 private   $supplier;
 private   $status;
 private   $fileName;
 private   $fileId;

    function __construct($supplier){
        $this->supplier=$supplier;
    }

   function downloadFile(){
       $ftp= new Ftp($this->supplier);
       $this->fileName=$ftp->download();
   }    

  function parseFile(){
      $parser= new Parser($this); // The parse needs the fileName in addition to the supplier info to parse the file correctly.
      $parser->parse();
  }

  function saveFileInfoToDB(){
  //Save file Info to db.
  }

}

所以每当我需要下载文件时,我都会执行以下操作:

 class ServiceInvoker{

 function downloadFilesFromFtpServers(){
     foreach($suppliers as $supplier){

    /*$supplier here is an object containing all data needed to download a file 
    from that certain supplier filled from the database 
    (i.e. ftpUsername, ftpPassword, ftpHost, SupplierName, supplierFileType).*/

     try{
     $file= new File($supplier);
     $file->downloadFile() 
     $file->saveFileInfoToDB(); 
      }catch(Exception $e){
       //log error
       }

   }
  }

}

您可以清楚地看到,要下载一个文件,我必须在不同的对象中进行多次下载调用。

我认为问题主要是因为我认为 File 类应该能够自行下载,因此我在 File 类本身中实例化了一个 Ftp 对象。

当我尝试解析文件时也会发生同样的情况,因为我需要将 $this 传递给解析器以获取文件的信息。

我认为 Ftp 类应该直接在 ServiceInvoker 中传递 Supplier 的对象,如果进程成功下载该文件,则使其返回 File 对象。

现在我应该如何正确识别类 Ftp Parser 和 File 之间的关系? File 是否应该包含解析器对象,或者解析器本身是否应该包含 File 对象并直接从服务调用程序调用?我可以清楚地将 Parser 和 File 类之间的关系识别为关联。 Ftp 和文件类之间相同,但谁应该包含谁?

【问题讨论】:

    标签: php uml associations class-design aggregation


    【解决方案1】:

    在我看来,您应该重新考虑文件的责任。可以下载文件,但这不是文件的责任。

    我的意思是 File 类应该概述 File 的属性和职责。下载文件的责任应该放在 DownloadManager 或类似的东西中。

    可以在 [SOLID design principle 中找到一些设计应用程序的重要指南,原理的起源可以在 Uncle Bob 的这篇论文中找到

    它为您提供了五个指导方针,为您提供松散耦合且更易于维护和重用的设计。关于这个主题有很多可用的资源。

    【讨论】:

    • +1 用于引用 SOLID OOP。这似乎是我的设计中真正缺乏的。
    猜你喜欢
    • 2020-09-25
    • 1970-01-01
    • 2023-03-30
    • 2016-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多