php工廠設計模式和單例模式相結合

<?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);
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章