基于php設(shè)計(jì)模式中工廠模式詳細(xì)介紹_PHP教程
推薦:基于php設(shè)計(jì)模式中單例模式的應(yīng)用分析本篇文章是對(duì)php設(shè)計(jì)模式中單例模式的應(yīng)用進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下
工廠模式:由工廠類根據(jù)參數(shù)來決定創(chuàng)建出哪一種產(chǎn)片類的實(shí)例
工廠類:一個(gè)專門用來創(chuàng)建其他對(duì)象的方法類。即按需分配,傳入?yún)?shù)進(jìn)行選擇,返回具體的類
作用:對(duì)象創(chuàng)建的封裝、簡化創(chuàng)建對(duì)象的操作,即調(diào)用工廠類的一個(gè)方法來得到需要的類
補(bǔ)充:
1.主要角色:抽象產(chǎn)品(Product)、具體產(chǎn)品(Concrete Product)、抽象工廠角色(Creator)
2.優(yōu)缺點(diǎn)
優(yōu)點(diǎn):工廠方法模式可以允許系統(tǒng)在不修改工廠角色的情況下引進(jìn)心產(chǎn)品
缺點(diǎn):客戶可能僅僅為了創(chuàng)建一個(gè)特定的Concrete Product對(duì)象,就不得不創(chuàng)建一個(gè)Creator子類
3.適用性
當(dāng)一個(gè)類不知道它所必須創(chuàng)建的對(duì)象的時(shí)候
當(dāng)一個(gè)類希望由它的子類來制定它所創(chuàng)建的對(duì)象的時(shí)候
當(dāng)一個(gè)類將創(chuàng)建對(duì)象的職責(zé)委托給多個(gè)幫助子類的某一個(gè),并且希望你將哪一個(gè)幫助子類是代理這一信息局部化的時(shí)候
<?php
//對(duì)象
class MyObject{
public function __construct(){}
public function test(){
return 'test';
}
}
//工廠
class MyFactory{
public static function factory(){
return new MyObject();
}
}
$myObject = MyFactory::factory();
echo $myObject->test();
?>
?<?php
//抽象類 定義屬性及抽象方法
abstract class Operation{
protected $_NumberA = 0;
protected $_NumberB = 0;
protected $_Result= 0;
public function __construct($A,$B){
$this->_NumberA = $A;
$this->_NumberB = $B;
}
public function setNumber($A,$B){
$this->_NumberA = $A;
$this->_NumberB = $B;
}
public function clearResult(){
$this->_Result = 0;
}
abstract protected function getResult();
}
//操作類
class OperationAdd extends Operation{
public function getResult(){
$this->_Result = $this->_NumbserA + $this->_NumberB;
return $this->_Result;
}
}
class OperationSub extends Operation{
public function getResult(){
$this->_Result = $this->_NumberA - $this->_NumberB;
return $this->_Result;
}
}
…………
//工廠類
class OperationFactory{
private static $obj;
public static function CreationOperation($type,$A,$B){
switch($type){
case '+':
self::$obj = new OperationAdd($A,$B);
break;
case '-':
self::$obj = new OperationSub($A,$B);
break;
……
}
}
}
//操作
$obj = OperationFactory:: CreationOperation('+',5,6);
echo $obj-> getResult();
?>
分享:深入解析php之sphinx本篇文章是對(duì)php中sphinx的使用進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下
- PHPNOW安裝Memcached擴(kuò)展方法詳解
- php記錄頁面代碼執(zhí)行時(shí)間
- PHP中獎(jiǎng)概率的抽獎(jiǎng)算法程序代碼
- apache設(shè)置靜態(tài)文件緩存方法介紹
- php對(duì)圖像的各種處理函數(shù)代碼小結(jié)
- PHP 關(guān)于訪問控制的和運(yùn)算符優(yōu)先級(jí)介紹
- 關(guān)于PHP語言構(gòu)造器介紹
- php/js獲取客戶端mac地址的實(shí)現(xiàn)代碼
- php5.5新數(shù)組函數(shù)array_column使用
- PHP preg_match的匹配多國語言的技巧
- php 中序列化和json使用介紹
- php采集文章中的圖片獲取替換到本地
- 相關(guān)鏈接:
- 教程說明:
PHP教程-基于php設(shè)計(jì)模式中工廠模式詳細(xì)介紹
。