1. 程式人生 > >PHP工廠模式計算面積與周長

PHP工廠模式計算面積與周長

shape 工廠 指定 ech def etc string new return

<?php
interface InterfaceShape
{
function getArea();
function getCircumference();
}

/**
* 矩形
*/
class Rectangle implements InterfaceShape
{
private $width;
private $height;
public function __construct($width,$height){
$this->width=$width;
$this->height=$height;
}
public function getArea(){
return $this->width*$this->height;
}
public function getCircumference(){
return 2*$this->width+2*$this->height;
}
}
/**
* 圓
*/
class circle implements InterfaceShape{
private $redius;
public function __construct($redius){
$this->redius = $redius;
}
public function getArea(){
return M_PI*pow($this->redius,2);
}
public function getCircumference(){
return M*PI*2*$this->redius;
}
}
class FactoryShape{//func_get_arg(索引)返回當前函數指定索引的參數值,返回string格式;
static public function create(){
switch (func_num_args()) {
case 1:
return new circle(func_get_arg(0));
case 2:
return new Rectangle(func_get_arg(0),func_get_arg(1));
default:
break;
}
}
}
$rect = FactoryShape::create(5,5);
var_dump($rect);
echo "<br>";
$circle = FactoryShape::create(4);
var_dump($circle);
?>

PHP工廠模式計算面積與周長