php設計模式 — Factory 方法模式(多態性原廠模式) (虛擬構造子模式)

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   使用   ar   strong   2014   

概念介紹:

Factory 方法模式: 在學習Factory 方法模式之前請首先閱讀簡單原廠模式
Factory 方法模式的用意是定義一個建立產品對象的工廠介面,將實際建立工作延遲到子類中.
Factory 方法模式是簡單原廠模式的進一步抽象和推廣

Factory 方法模式的幾個需要的對象:

1、抽象工廠

2、具體工廠:實現抽象工廠介面列出的方法,並且每個工廠對應各自的產品

3、抽象產品

4、具體產品

 

Factory 方法模式裡面的果園的例子,可以改寫成Factory 方法模式 , 大家可以自己實驗。

案例圖:

 

代碼執行個體:
 1 <?php 2  3 //此執行個體是根據女媧造人寫的 4  5 //首先定義一個全域的工廠介面 6 //由陰繩 陽繩來繼承 都要實現舉繩子這個方法 7 interface nvwaRope{ 8     public function liftRope($name); 9 }10 11 //定義陰繩 來繼承 nvwaRope12 class yinRope implements nvwaRope{13     public function liftRope($name){14         return new boy($name);15     }16 }17 18 //定義陽繩 19 class yangRope implements nvwaRope{20     public function liftRope($name){21         return new girl($name);22     }23 }24 25 26 //定義一個人的抽象介面27 interface people{28     public function eat();29     public function getName();30 }31 32 33 abstract class abstractPeople implements people{34     private $name;35 36     public function __construct($name){37         $this->name = $name;38     }39 40     public function eat(){41         echo $this->name . " eat";42     }43 44     public function getName(){45         echo $this->name;46         return $this->name;47     }48 49     //檢查是否有胸50     public function checkChest(){51         return $this->haveChest;52     }53 }54 55 class boy extends abstractPeople{56     public $haveChest = false; //男孩沒有胸57 }58 59 class girl extends abstractPeople{60     public $haveChest = true; //女孩有胸61 }62 63 64 65 //使用方式66 67 //首先擷取工廠的執行個體 也就是陰繩或者陽繩的執行個體68 $yinRope = new yinRope();69 70 $people = $yinRope->liftRope("張三");71 echo $people->eat();72 echo $people->getName();73 var_dump($people->checkChest());

 

php設計模式 — Factory 方法模式(多態性原廠模式) (虛擬構造子模式)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.