Example of php factory pattern

无忌哥哥
Release: 2023-04-01 21:36:02
Original
1240 people have browsed it

* Singleton mode: used to create a unique instance object of a single type

* Factory mode: used to create multiple instance objects of multiple types

//Declaration of shape classes

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;
                
        }
    }
}
Copy after login

//Declare the rectangle class

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;
    }
}
Copy after login

//Declare the triangle class

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;
    }
}
Copy after login

//Use static methods to instantiate the shape class instead of using the traditional new keyword

//According to different shape type parameters, instantiate different classes and generate different objects

$rectangle = Shape::create('rectangle',[10,30]);
echo '长方形的面积是'.$rectangle->area();
echo &#39;<hr>&#39;;
$triangle = Shape::create(&#39;triangle&#39;,[20,50]);
echo &#39;三角形的面积是&#39;.$triangle->area();
Copy after login

The above is the detailed content of Example of php factory pattern. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template