Heim  >  Artikel  >  php教程  >  基于php设计模式中工厂模式详细介绍

基于php设计模式中工厂模式详细介绍

WBOY
WBOYOriginal
2016-06-13 11:52:11894Durchsuche

工厂模式:由工厂类根据参数来决定创建出哪一种产片类的实例
工厂类:一个专门用来创建其他对象的方法类。即按需分配,传入参数进行选择,返回具体的类
作用:对象创建的封装、简化创建对象的操作,即调用工厂类的一个方法来得到需要的类
补充:
1.主要角色
:抽象产品(Product)、具体产品(Concrete Product)、抽象工厂角色(Creator)
2.优缺点
    优点:工厂方法模式可以允许系统在不修改工厂角色的情况下引进心产品
    缺点:客户可能仅仅为了创建一个特定的Concrete Product对象,就不得不创建一个Creator子类
3.适用性
    当一个类不知道它所必须创建的对象的时候
    当一个类希望由它的子类来制定它所创建的对象的时候
    当一个类将创建对象的职责委托给多个帮助子类的某一个,并且希望你将哪一个帮助子类是代理这一信息局部化的时候

复制代码 代码如下:


//对象
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();
?>
 

?//抽象类 定义属性及抽象方法
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();
?>

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn