* 單例模式:用於建立單一類型的唯一執行個體對象
* 原廠模式:用於建立多種類型的多個執行個體對象
//聲明形狀類
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();