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