PHP中鮮為人知的設計模式The FlyWater模式通過重複使用先前創建的對象來優化內存使用情況。 它沒有反复創建相同的對象,而是將其存儲並從池中檢索,避免了冗餘資源分配。 將其視為一個複雜的對象工廠,在創建新對象之前檢查現有對象。
此模式在處理大量大文件的應用中閃耀,每個文件都充當輕量級對象。
密鑰概念:
>
輕量級工廠示例:
File
使用一個關聯陣列(data
)存儲創建的對象,由文件路徑鍵入(唯一標識符)。
<code class="language-php">class File { private $data; public function __construct($filePath) { if (!file_exists($filePath)) { throw new InvalidArgumentException('File not found: ' . $filePath); } $this->data = file_get_contents($filePath); } public function getData() { return $this->data; } }</code>使用工廠確保僅加載文件一次:
線程和內存管理:
FileFactory
>
在多線程環境中,蒼蠅模式的不變性可確保線程安全性。但是,應使用鎖定機制將工廠方法視為關鍵部分,以防止並發對象創建。 在PHP中,如果工廠無限期存儲對對象的引用,則可能發生內存洩漏。因此,該模式最適合具有預定數量有限的對象的場景。
$files
<code class="language-php">class FileFactory { private $files = []; public function getFile($filePath) { if (!isset($this->files[$filePath])) { $this->files[$filePath] = new File($filePath); } return $this->files[$filePath]; } }</code>
>輕量級模式對於創建枚舉對像也很有價值,如在諸如Doctrine dbal之類的庫中所示。這樣可以確保每個枚舉值僅存在一個實例。 考慮這個簡化的示例:
<code class="language-php">$factory = new FileFactory; $fileA = $factory->getFile('/path/to/file.txt'); $fileB = $factory->getFile('/path/to/file.txt'); if ($fileA === $fileB) { echo 'Same object!'; }</code>
<code class="language-php">class File { private $data; public function __construct($filePath) { if (!file_exists($filePath)) { throw new InvalidArgumentException('File not found: ' . $filePath); } $this->data = file_get_contents($filePath); } public function getData() { return $this->data; } }</code>
此方法通過確保每種類型的一致對象身份來降低內存使用情況並提高代碼的清晰度。
摘要:
當對象共享顯著降低內存消耗時,以上是輕量級設計模式和不變性:完美的匹配的詳細內容。更多資訊請關注PHP中文網其他相關文章!