体婪柒鲁芭揩补阶扛赌纤无灿
单例模式:用于创建单一类型的唯一实例对象
工厂模式:用于创建多种类型的多个实例对象
新建demo2.php
<?php /* * 单例模式:用于创建单一类型的唯一实例对象 * 工厂模式:用于创建多种类型的多个实例对象 */ //$obj = create($class); //根据不同形状,计算面积 class Shape { 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($width,$height) { $this->width=$width; $this->height=$height; } //计算面积 public function area() { return $this->width * $this->height; } } //三角形 class Triangle { private $width; private $height; public function __construct($width,$height) { $this->width=$width; $this->height=$height; } //计算面积 public function area() { return ($this->width * $this->height)/2; } } //实例化形状类 $rectangle=Shape::create('rectangle',[20,30]); echo "长方形的面积是:".$rectangle->area()."<br>"; echo "<br>"; $triangle=Shape::create('triangle',[20,50]); echo "三角形的面积是:".$triangle->area()."<br>";
执行:
射瓢绒黎鲁返天丹瑞旱舞恍楷