php原廠模式的執行個體說明

來源:互聯網
上載者:User
* 單例模式:用於建立單一類型的唯一執行個體對象

* 原廠模式:用於建立多種類型的多個執行個體對象

//聲明形狀類

class Shape{    //聲明靜態方法create,根據容器形狀不同,建立不同圖形類的執行個體    public static function create($type,array $size=[])    {        //檢測形狀?        switch ($type)        {            //長方形            case 'rectangle':                return new Rectangle($size[0],$size[1]);                break;                        //三角形            case 'triangle':                return new Triangle($size[0],$size[1]);                break;                        }    }}

//聲明長方形類

class Rectangle{    private $width;  //寬度    private $height; //進階    public function __construct($witch,$height)    {        $this->width = $witch;        $this->height = $height;    }        //計算長方形面積: 寬 * 高    public function area()    {        return $this->width * $this->height;    }}

//聲明三角形類

class Triangle{    private $bottom;  //底邊    private $height;  //邊長    public function __construct($bottom,$height)    {        $this->bottom = $bottom;        $this->height = $height;    }        //計算三角形面積:  (底 * 高) / 2    public function area()    {        return ($this->bottom * $this->height)/2;    }}

//使用靜態方法來執行個體化形狀類,而不是用傳統的new 關鍵字

//並根據形狀型別參數的不同,來執行個體化不同的類,產生不同的對象

$rectangle = Shape::create('rectangle',[10,30]);echo '長方形的面積是'.$rectangle->area();echo '<hr>';$triangle = Shape::create('triangle',[20,50]);echo '三角形的面積是'.$triangle->area();

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.