php工厂模式

本文介绍了一种设计模式——工厂模式,并通过创建不同形状类的实例来演示其使用方法。具体展示了如何通过传递参数自动创建圆形和矩形类的实例,并实现计算面积和周长的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值