设计模式 工厂模式

简单工厂模式主要由接口、接口的实现、工厂类这三个组成。

使用者通过调用工厂类的create方法,并传入不同的变量来选择所需要生成的类的实例(之前接口的实现)

<?php
      
    // 定义一个统一的接口
    interface InterfaceShape
    {
     function getArea();
     function getCircumference();
    }
      
    /**
    * 接口的实现_矩形
    */
    class Rectangle implements InterfaceShape
    {
      private $width;
      private $height;
       
      public function __construct($width, $height)
      {
        $this->width = $width;
        $this->height = $height;
      }
      
      public function getArea()
      {
        return $this->width* $this->height;
      }
      
      public function getCircumference()
      {
        return 2 * $this->width + 2 * $this->height;
      }
    }
      
    /**
    * 接口的实现_圆形
    */
    class Circle implements InterfaceShape
    {
      private $radius;
      
      function __construct($radius)
      {
        $this->radius = $radius;
      }
      
      
      public function getArea()
      {
        return M_PI * pow($this->radius, 2);
      }
      
      public function getCircumference()
      {
        return 2 * M_PI * $this->radius;
      }
    }
      
    /**
    * 形状工厂类
    */
    class FactoryShape
    {
      public static function create()
      {
      	// func_num_args用于判断传入参数的数量
        switch (func_num_args()) {
          case1:
          return newCircle(func_get_arg(0));
          case2:
          // func_get_arg(0)获取传入的第几个参数
          return newRectangle(func_get_arg(0), func_get_arg(1));
          default:
            # code...
            break;
        }
      }
    }
      
    $rect =FactoryShape::create(5, 5);
    var_dump($rect);
    echo "<br>";
      
    $circle =FactoryShape::create(4);
    var_dump($circle);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值