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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值