zoukankan      html  css  js  c++  java
  • Factory工厂模式复习

    工厂设计模式 用于创建多种类型的多个实例对象

    class Factory{
        //声明静态方法create,根据不同的形状,创建不同的图形类的实例
        public static function create($type,array $size=[]) {
            //检测形状
            switch ($type) {
                //长方形
                case 'rectangle': 
                    return new Rectangle($size[0],$size[1]);
                break;
                //三角形
                case 'triangle':
                    return new Triangle($size[0],$size[1]);
                break;
            }
        }
    }
    //声明长方形类
    class Rectangle{
        private $width;
        private $height;
        public function __construct($width,$height) {
            $this->height = $height;
            $this->width = $width;
        }
        public function area() {
            return $this->width * $this->height;
        }
    }
    //声明三角形类
    class Triangle{
        private $bottom;  //底边
        private $height;  //边长
        public function __construct($bottom,$height){
            $this->bottom = $bottom;
            $this->height = $height;
        }
        //计算三角形面积:  (底 * 高) / 2
        public function area() {
            return ($this->bottom * $this->height)/2;
        }
    }
    
    //使用静态方法来实例化形状类,而不是用传统的new 关键字
    //并根据形状类型参数的不同,来实例化不同的类,生成不同的对象
    $rectangle = Factory::create('rectangle',[10,30]);
    echo '长方形面积是'.$rectangle->area();
    echo '<br>';
    $triangle = Factory::create('triangle',[10,30]);
    echo '三角形面试是'.$triangle->area();
    

      

    每天学习一点,日积月累最终会汇成大海!
  • 相关阅读:
    docker基础命令
    oracle 控制文件损坏处理
    mongodb 分片技术
    replcation set (复制集)配置过程 --mongodb
    redis API ---python
    MHA 高可用架构部署
    innoback 参数及使用说明
    Windows服务创建及发布
    DevOps 什么是 CI/CD?
    .NETReflectorVisualStudioExtension
  • 原文地址:https://www.cnblogs.com/viczhang/p/11410669.html
Copyright © 2011-2022 走看看