Rumah  >  Artikel  >  pembangunan bahagian belakang  >  PHP模板+工厂设计模式

PHP模板+工厂设计模式

WBOY
WBOYasal
2016-06-20 12:35:04916semak imbas

```<?php/** * Created by PhpStorm. * User: gewenrui * Date: 16/3/11 * Time: 上午8:48 */namespace  practice;abstract  class Fruit{    protected $apple;    protected $pineapple;    public  function  templateMethod(){         $this->addApple();         $this->addPineapple();    }    abstract  protected  function  addApple();    abstract  protected  function  addPineapple();}//创建一个子类实现父类的模板内的方法class TF extends Fruit{    protected function addApple()    {   //生成一个工厂        $this->apple =  new AppleFactory();        //调用方法        echo $this->apple->doFactory();    }    protected function addPineapple()    {        $this->pineapple = new PineAppleFactory();        echo $this->pineapple->doFactory();    }}class PineAppleFactory extends Creator{    protected function doFacoryMethod()    {        $product  = new PineApple();        return $product->getAttribute();    }}class PineApple implements Product{    private $mfg;    public function getAttribute()    {        $this->mfg = "pineapple";        return $this->mfg;    }}abstract class Creator{    abstract protected function doFacoryMethod();    public function  doFactory(){        $mfg = $this->doFacoryMethod();        return $mfg;    }}//设置一个产品的接口interface  Product{    public  function getAttribute();}class AppleFactory extends Creator{    protected function doFacoryMethod()    {        $product  = new Apple();        return $product->getAttribute();    }}class Apple implements Product{    private  $mfg;    public function getAttribute()    {        $this->mfg = "apple";        return $this->mfg;    }}class Client{    public function  __construct()    {        $qq = new TF();        $qq->templateMethod();    }}$data = new Client();```

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel sebelumnya:新人、中奖概率问题Artikel seterusnya:PHP扩展问题