php工厂模式的实例

* 单例模式:用于创建单一类型的唯一实例对象
* 工厂模式:用于创建多种类型的多个实例对象

//声明形状类

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