Heim  >  Artikel  >  Backend-Entwicklung  >  PHP模板+工厂设计模式

PHP模板+工厂设计模式

WBOY
WBOYOriginal
2016-06-20 12:35:04916Durchsuche

```<?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();```

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
Vorheriger Artikel:新人、中奖概率问题Nächster Artikel:PHP扩展问题