<?php
/*工厂设计模式常用于根据输入参数的不同或者应用程序配置的不同来创建一种专门用来实例化并返回其对应的类的实例。
我们举例子,假设矩形、圆都有同样的一个方法,那么我们用基类提供的API来创建实例时,通过传参数来自动创建对应的类的实例,他们都有获取周长和面积的功能。*/
interface Shape {
public function area();
public function grith();
}
class Circle implements Shape {
class Circle implements Shape {
private $radius;
public function __construct($arr) {
$this->radius = $arr[0];
}
public function area() {
return 3.14 * $this->radius * $this->radius;
}
public function grith() {
return 6.28 * $this->radius;
}
}
class Rect implements Shape {
private $length;
private $width;
public function __construct($arr) {
$this->length = $arr[0];
$this->width = $arr[1];
}
public function area():float {
return $this->length * $this->width;
}
public function grith():float {
return 2 * ($this->length + $this->width);
}
}
class Count {
public static $shape;
const LIST = [
1 => 'Circle',
2 => 'Rect',
];
public static function get_instance(...$arr) {
$arr = func_get_args();
$attr_num = count($arr);
$shape = static::LIST[$attr_num];
return static::$shape = new $shape($arr);
}
}
$shape = Count::get_instance(5);
var_dump($shape->area(), $shape->grith());