<?php
/*工厂设计模式和单例模式相结合*/
//各种图形公共接口
interface Shape {
public function area();
public function grith();
}
//圆单例
class Circle implements Shape {
private static $radius = 0;
private static $single;
private function __clone() {
}
private function __construct($arr) {
static::$radius = $arr[0];
}
public function get_instance($arr) {
if (static::$single instanceof static) {
static::$radius = $arr[0];
return static::$single;
}
return static::$single = new static($arr);
}
public function area():float {
return 3.14 * static::$radius * static::$radius;
}
public function grith():float {
return 6.28 * static::$radius;
}
}
//矩形单例
class Rect implements Shape {
private static $length = 0;
private static $width = 0;
private static $single;
private function __construct($arr) {
static::$length = $arr[0];
static::$width = $arr[1];
}
private function __clone() {
}
public function get_instance($arr) {
if (static::$single instanceof static) {
static::$length = $arr[0];
static::$width = $arr[1];
return static::$single;
}
return static::$single = new static($arr);
}
public function area():float {
return static::$length * static::$width;
}
public function grith():float {
return 2 * (static::$length + static::$width);
}
}
//对外公开调用类
class Count {
const LIST = [
1 => 'Circle',
2 => 'Rect',
];
public static function get_shape(...$arr) {
$arr = func_get_args();
$shape = static::LIST[count($arr)];
return $shape::get_instance($arr);
}
}
$shape = Count::get_shape(5);var_dump($shape->area(), $shape->grith());
$shape2 = Count::get_shape(6);var_dump($shape2->area(), $shape2->grith(), $shape === $shape2);
$shape3 = Count::get_shape(5,5);var_dump($shape3->area(), $shape3->grith());
$shape4 = Count::get_shape(6,6);var_dump($shape4->area(), $shape4->grith(), $shape3 === $shape4);