深入理解PHP:高级技巧、面向对象与核心技术(原书第3版) -- 设计模式之工厂模式

来源:互联网 发布:电信光猫有几个端口 编辑:程序博客网 时间:2024/04/30 01:31
<?php// 设计思想:创建型模式,和单一模式不同,此设计思想用来创建不同类型的多个对象。// 适用于:程序编写时候,并不清楚它的确切对象类型,只有应用运行时候,才能确定。适用于动态的应用程序中。abstract class ShapeFactory{    static function Create($type, array $sizes)    {     // 工厂模式标志,一般名称为 Create,factory,factoryMethod,createInstance 此方法用来创建不同类型的多个对象。        switch ($type) {            case "rectangle":                return new Rectangle($sizes[0], $sizes[1]);                break;            case "triangle":                return new Triangle($sizes[0], $sizes[1], $sizes[2]);                break;        }    }}class Rectangle{    public $width = 0;    public $height = 0;    function __construct($w = 0, $h = 0)    {        $this->width = $w;        $this->height = $h;    }    function setSize($w = 0, $h = 0)    {        $this->width = $w;        $this->height = $h;    }    function getArea()    {        return ($this->width * $this->height);    }    function getPerimeter()    {        return (($this->width + $this->height) * 2);    }    function isSquare()    {        if ($this->width == $this->height) {            return true; // Square        } else {            return false; // Not a square        }    }}class Triangle{    private $_sides = array();    private $_perimeter = NULL;    function __construct($s0 = 0, $s1 = 0, $s2 = 0)    {        $this->_sides[] = $s0;        $this->_sides[] = $s1;        $this->_sides[] = $s2;        $this->_perimeter = array_sum($this->_sides);    }    public function getArea()    {        return (SQRT(            ($this->_perimeter / 2) *            (($this->_perimeter / 2) - $this->_sides[0]) *            (($this->_perimeter / 2) - $this->_sides[1]) *            (($this->_perimeter / 2) - $this->_sides[2])        ));    }    public function getPerimeter()    {        return $this->_perimeter;    }}// 为了体现其动态特性,可用 http 协议 get 传值。// http://some.com?name=triangle&size[]=4&size[]=2&size[]=3$obj = ShapeFactory::Create("triangle", [4, 2, 3]);echo $obj->getArea();echo "\n";echo $obj->getPerimeter();echo "\n";$obj = ShapeFactory::Create("rectangle", [1, 3]);echo $obj->getArea();echo "\n";echo $obj->getPerimeter();echo "\n";
阅读全文
0 0
原创粉丝点击