zoukankan      html  css  js  c++  java
  • 【PHP设计模式 08_CeLue.php】策略模式

    <?php 
    /**
     * 【策略模式】----和“简单工厂”模式很相似
     * 根据不同运算符计算两个数的运算结果
     * 常规方式就是判断运算符然后进行if...else的操作
     * 现在使用“策略模式”
     */
    
    header("Content-type: text/html; charset=utf-8");
    
    if(isset($_POST['js']) && !empty($_POST['js'])){
        /*接口,和四个真实计算器*/
        interface Math{
            public function calc($op1,$op2);
        }
        class Jia implements Math{
            public function calc($op1, $op2){
                return $op1+$op2;
            }
        }
        class Jian implements Math{
            public function calc($op1, $op2){
                return $op1-$op2;
            }
        }
        class Cheng implements Math{
            public function calc($op1, $op2){
                return $op1*$op2;
            }
        }
        class Chu implements Math{
            public function calc($op1, $op2){
                return $op1/$op2;
            }
        }
        
        /*封装一个虚拟计算器*/
        class CMath{
            protected $jisuan = null;
            //$objType 对应的真实计算器的 Jia/Jian/Cheng/Chu
            public function __construct($type){
                if($type==1){
                    $objType = 'Jia';
                }elseif($type==2){
                    $objType = 'Jian';
                }elseif($type==3){
                    $objType = 'Cheng';
                }elseif($type==4){
                    $objType = 'Chu';
                }else{
                    exit('Error...');
                }
                $this->jisuan = new $objType();
            }
            public function jsq($num1,$num2){
                return $this->jisuan->calc($num1,$num2); 
            }
        }
        
        /*开始调用*/
        $js = $_POST['js'];
        $cmath = new CMath($js);
        $res = $cmath->jsq($_POST['num1'], $_POST['num2']);
        echo $res;
        
        
    }
    
    ?>
    
    
    <form action="?" method="post">
    <input type="text" name="num1">
    <select name="js">
        <option value="1">+</option>
        <option value="2">-</option>
        <option value="3">*</option>
        <option value="4">/</option>
    </select>
    <input type="text" name="num2">
    <button type="submit">提交</button>
    </form>
  • 相关阅读:
    Redis订阅和发布模式和Redis事务
    Redis介绍和环境安装
    Redis基本数据类型
    MongoDB导入导出以及数据库备份
    MongoDB-python的API手记
    MongoDB对应SQL语句
    判断是否微信浏览器访问并得到微信版本号
    windows 下编译php扩展库pecl里的扩展memcache
    用PHPExcel类读取excel文件的内容
    用excel.php类库导出excel文件
  • 原文地址:https://www.cnblogs.com/rxbook/p/6002992.html
Copyright © 2011-2022 走看看