设计模式-工厂方法
作者:edwin
日期:2019-08-05 14:58:16
所属分类:后端 - php

决定该模式定义了一个创建对象的接口而让子类决定哪个类来实例化它允许一个类延迟实例化到子类

ConcreteCreator(具体创建者)
This class overrides the factory method to return an instance of a ConcreteProduct.
(这类覆盖了工厂方法返回一个ConcreteProduct的一个实例。)

Creator(创建者)
This class (a) declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object, and (b) may call the factory method to create a Product object.
(这类(a)声明了工厂方法,该方法返回一个类型产品的对象。创造者也可能定义一个工厂方法的默认实现返回一个默认的ConcreteProduct对象,和(b)可以调用工厂方法创建产品对象。)

ConcreteProduct(具体产品)
This class implements the Product interface.
(这个类实现了产品接口。)

Product(产品)
This class defines the interface of objects the factory method creates.
(这个类定义了工厂方法创建的对象的接口)

代码实现

<?php

class FactoryAdd extends abstract_factory
{
    public static function GreateClass()
    {
        return new OperationAdd();
    }
}

abstract class abstract_factory
{
    abstract public static function GreateClass();
}

class OperationAdd extends Abstract_Operation
{
    public function GetResult()
    {
        $result = $this->Getnuma() + $this->Getnumb();
        return $result;
    }
}

abstract class Abstract_Operation
{

    /**
     * 定义私有变量
     * 
     * @var $numa
     */
    private $numa;

    /**
     * 定义私有变量
     * 
     * @var $numb
     */
    private $numb;

    public function Getnuma()
    {

        return $this->numa;
    }

    public function Setnuma($num)
    {

        $this->numa = $num;
    }

    public function Getnumb()
    {

        return $this->numb;
    }

    public function Setnumb($num)
    {

        $this->numb = $num;
    }


    /**
     * 抽象方法GetResult 返回结果
     * 
     */
    abstract protected function GetResult();

}

$oper = FactoryAdd::GreateClass();
$oper->Setnuma(1);
$oper->Setnumb(2);
$oper->GetResult();

评论

全部评论 / 0