当前位置 : 主页 > 网络编程 > PHP >

简单的一个工厂模式代码

来源:互联网 收集:自由互联 发布时间:2021-07-03
?php// factory pattern class Shape { static public function getShape($type, $dimension) { if ($type $dimension) { switch($type) { case 'circle': return new Circle($dimension); break; case 'square': return new Square($dimension); break; defa
 
<?php
// factory pattern
  
class Shape {
    static public function getShape($type, $dimension) {
  
        if ($type && $dimension) 
        {
            switch($type)
            {
                case 'circle':
                    return new Circle($dimension);
                break;
  
                case 'square':
                    return new Square($dimension);
                break;
  
                default:
                    throw new Exception("Unrecognized shape");                  
                break;
            }           
        }
    }
}
  
class Circle {
    private $radius = 0;
    public function __construct($radius) {
        $this->radius = $radius;
    }
    public function getArea() {
        return $this->radius * $this->radius * pi();
    }
}
  
class Square {
    private $side = 0;
    public function __construct($side) {
        $this->side = $side;
    }
    public function getArea() {
        return $this->side * $this->side;
    }
}
  
$shape = Shape::getShape('circle', 10);
echo $shape->getArea();
echo "\\n";
  
$shape = Shape::getShape('square', 2);
echo $shape->getArea();
echo "\\n";

网友评论