本篇文章給大家帶來的內容是關于PHP設計模式:php工廠模式的介紹(附代碼),有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。
工廠模式是一種隱藏類的實例化細節,并且對一系列類使用相同的實例化方式,可以很方便的擴展更多的實現同一個接口的類的創建對象的方式。
示例應用場景有:
1)在線支付
支付有多種方式,比如微信支付,支付寶支付,銀聯支付等,根據用戶的選擇而采用相應的支付方式;
2)訪問量統計
在一個業務較復雜的項目中,用戶對不同的對象進行訪問,比如訪問文章、訪問作者、訪問文章目錄等,同樣是訪問記錄,記錄的信息卻不一樣
工廠模式的原理:
先根據多個對象的相同行為設計一個接口,再讓這幾個類去實現這個接口,接著制造一個實例化工廠,即可在工廠中根據不同參數實例化不同類。
工廠模式的具體實現:
/* * 形狀接口 */interface Shape{ html' target='_blank'>public function area();}/* * 長方形類,實現了形狀接口 */class Rectangle implements Shape{ private $long; private $width; function __construct($long,$width) $this- long = $long; $this- width = $width; } /* * 實現面積方法 public function area() // TODO: Implement area() method. return $this- long * $this- width; * 正方形類,實現了形狀接口 */class Square implements Shape{ private $width; function __construct($width) $this- width = $width; } /* * 實現面積方法 public function area() // TODO: Implement area() method. return pow($this- width,2); * 圓形類,實現了形狀接口 */class Circle implements Shape{ private $radiu; function __construct($radiu) $this- radiu = $radiu; } /* * 實現面積方法 public function area() // TODO: Implement area() method. return pi()*pow($this- radiu,2);}class ShapeFactory{ * 獲取實例化的形狀對象 * ...$args 表示接受不限個數的參數 public function getShpae(...$args) * 第一個參數為形狀名,后面的參數為形狀的尺寸 switch($args[0]) { case Rectangle : return new Rectangle($args[1],$args[2]); break; case Square : return new Square($args[1]); break; case Circle : return new Circle($args[1]); break; } return null;}$factory = new ShapeFactory();$shape = $factory- getShpae( Rectangle ,2,3);$area[] = $shape- area();$shape = $factory- getShpae( Square ,2);$area[] = $shape- area();$shape = $factory- getShpae( Circle ,2);$area[] = $shape- area();print_r($area);/*Array [0] = 6 [1] = 4 [2] = 12.566370614359*/
相關文章推薦:
php如何獲取文件一級目錄(純代碼)
php如何利用經度和緯度來計算兩點之間的距離(純代碼)
以上就是PHP設計模式:php工廠模式的介紹(附代碼)的詳細內容,PHP教程
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。
新聞熱點
疑難解答