Go设计模式(4)-代码编写优化

简介: 前段日子写了 Go设计模式(4)-代码编写 但当时写的比较急,文章里代码写的其实并不是很好,所以抽时间又优化了一次。这次虽然还是不完美,但比上次要好不少。

前段日子写了 Go设计模式(4)-代码编写 但当时写的比较急,文章里代码写的其实并不是很好,所以抽时间又优化了一次。这次虽然还是不完美,但比上次要好不少。

这次还有一些优化点,大家可以找一下,看看哪些地方能够继续提升。

<?php
//工具类
class Utils {
    //返回当前的毫秒时间戳
    public function msectime() {
        list($msec, $sec) = explode(' ', microtime());
        $msectime         = (float) sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectime;
    }
    //拼接URL
    public function buildQuery($url,$arr) {
        return $url."?".http_build_query($arr);
    }
}
//Http客户端
class HttpClient {
    //http Get请求
    function sendGetRequest($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_TIMEOUT, 5);
        curl_setopt($curl, CURLOPT_URL, $url);
        $output    = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
    //http Post请求
    function sendPostRequest($url,$postData) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
}
//和医院系统交互类
class HospitalOperation {
    public $httpClient;
    public $hospital;
    public $utils;
    function __construct($hospital) {
        $this->httpClient = new HttpClient();
        $this->hospital = $hospital;
        $this->utils = new Utils();
    }
    //1.获取个人id
    public function getUserId() {
        var_dump("开始执行getUserId");
        $url = $this->utils->buildQuery($this->hospital->getUinfoUrl(),$this->hospital->getUinfoParams());
        $uInfo   = $this->httpClient->sendGetRequest($url);
        if(empty($uInfo)) {
            var_dump("执行getUserId失败");
            return -1;
        }
        $res = $this->hospital->getUid($uInfo);
        if(empty($res)) {
            var_dump("获取getUserId失败");
            return -1;
        }
        var_dump("getUserId成功,结果为",$res);
        $this->hospital->setRecordData($res);
        return 0;
    }
    //2.获取病人id
    public function getPatientId() {
        var_dump("开始执行getPatientId");
        $url = $this->utils->buildQuery($this->hospital->getPatientUrl(),$this->hospital->getPatientParams());
        $listInfo   = $this->httpClient->sendGetRequest($url);
        if(empty($listInfo)) {
            var_dump("执行getPatientId失败");
            return -1;
        }
        $res = $this->hospital->getPatientId($listInfo);
        if(empty($res)) {
            var_dump("获取getPatientId失败");
            return -1;
        }
        var_dump("getPatientId成功,patientId为",$res);
        $this->hospital->setRecordData($res);
        return 0;
    }
    //3.获取医生可用时间段的id
    public function getBresPeakId() {
        var_dump("开始执行getBresPeakId");
        $url = $this->utils->buildQuery($this->hospital->getBresPeakUrl(),$this->hospital->getBresPeakParams());
        $bresInfo  = $this->httpClient->sendGetRequest($url);
        if(empty($bresInfo)) {
            var_dump("执行getBresPeakId失败");
            return -1;
        }
        $res = $this->hospital->getBresPeakId($bresInfo);
        if(empty($res)) {
            var_dump("获取getBresPeakId失败");
            return -1;
        }
        var_dump("获取getBresPeakId成功",$res);
        $this->hospital->setRecordData($res);
        return 0;
    }
    //4.注册
    public function registe() {
        var_dump("开始执行registe");
        $url = $this->utils->buildQuery($this->hospital->getRegistUrl(),$this->hospital->getRegistParams());
        $postData = $this->hospital->getRegistPostData();
        $regInfo = $this->httpClient->sendPostRequest($url,$postData);
        $res = $this->hospital->getRegistRes($regInfo);
        if(empty($res)) {
            var_dump('registe failed',$postData);
        } else {
            var_dump('registe success',$postData,$res);
        }
        return $res;
    }
    //5.执行整个流程
    function run() {
        $res = $this->getUserId();
        if($res == -1) {
            exit;
        }
        $res = $this->getPatientId();
        if($res == -1) {
            exit;
        }
        $res = $this->getBresPeakId();
        if($res == -1) {
            exit;
        }
        $this->registe();
    }
}
//返回数据解码
class Decode {
    public function decodeFunc($data) {
        $data = json_decode($data, true);
        return $data;
    }
}
//医院类
class Hospital {
    protected $wxId;
    //微信ID
    protected $regDepId;
    //预约诊室
    protected $docName;
    //医生姓名
    protected $patientName;
    //患者姓名
    protected $regDay;
    //看病日期
    protected $uInfoUrl;
    //根据微信号获取个人信息URL
    protected $patientListUrl;
    //获取患者列表URL
    protected $bresPeakUrl;
    //医生出诊时间URL
    protected $regUrl;
    //注册URL
    protected $uId;
    //微信ID对应的用户ID
    protected $recordData = array();
    //注册需要提交的数据
    public $utils;
    //工具类
    public $decode;
    //接口返回数据解析方式
    function __construct($config,$regDepId,$docName,$patientName,$regDay,$decode) {
        $this->wxId = $config['wxId'];
        $this->uInfoUrl = $config['uInfoUrl'];
        $this->patientListUrl = $config['patientListUrl'];
        $this->bresPeakUrl = $config['bresPeakUrl'];
        $this->regUrl = $config['regUrl'];
        $this->regDepId = $regDepId;
        $this->docName = $docName;
        $this->patientName = $patientName;
        $this->regDay = $regDay;
        $this->decode = $decode;
        $this->utils = new Utils();
    }
    /**
     * 中间结果记录
     */
    final public function setRecordData($data) {
        foreach ($data as $key => $value) {
            $this->recordData[$key] = $value;
        }
    }
    final public function getRecordData():array {
        return $this->recordData;
    }
    /**
     * url相关
     */
    final public function getUinfoUrl():string {
        return $this->uInfoUrl;
    }
    final public function getPatientUrl():string {
        return $this->patientListUrl;
    }
    final public function getBresPeakUrl():string {
        return $this->bresPeakUrl;
    }
    final public function getRegistUrl():string {
        return $this->regUrl;
    }
    public function getUinfoParams():array {
    }
    //子类需重写
    public function getPatientParams():array {
    }
    //子类需重写
    public function getBresPeakParams():array {
    }
    //子类需重写
    public function getRegistParams():array {
    }
    //子类需重写
    public function getRegistPostData():array {
    }
    //子类需重写
    /**
     * 获得微信对应的用户id,空表示获取失败
     * 子类需重写
     */
    public function getUid($res):array {
    }
    /**
     * 获得患者Id,空表示获取失败
     * 子类需重写
     */
    public function getPatientId($res):array {
    }
    /**
     * 获得医生问诊时段Id,空表示获取失败
     * 子类需重写
     */
    public function getBresPeakId($res):array {
    }
    /**
     * 获得注册结果,空表示注册失败
     * 子类需重写
     */
    public function getRegistRes($res):array {
    }
}
/**
 * Class HospitalA
 * 继承自Hospital类,主要用于
 * 1. 生成各个接口的URL
 * 2. 解析返回数据,获取想要的结果
 * 3. 最终生成注册的数据postData
 */
class HospitalA extends Hospital {
    /**
     * url请求参数相关
     */
    public function getUinfoParams():array {
        return array(
            'act'=>'userinfo_oid',
            'uid'=>$this->wxId,
            'tm'=>$this->utils->msectime(),
            'oid'=>$this->wxId,
        );
    }
    public function getPatientParams():array {
        $recordData = $this->getRecordData();
        return array(
            'act'=>'member',
            'uid'=>$recordData['uid'],
            'oid'=>$this->wxId,
        );
    }
    public function getBresPeakParams():array {
        return array(
            'act'=>'bespeak_v1',
            'deptid'=>$this->regDepId,
            'clsid' => 2, //专家号
            'tm'=>$this->utils->msectime(),
        );
    }
    public function getRegistParams():array {
        return array(
            'act'=>'bespeak',
        );
    }
    public function getRegistPostData():array {
        $recordData = $this->getRecordData();
        return array(
            'oid' => $this->wxId,
            'uid' => $recordData['uid'],
            'sickid' => $recordData['sickid'],
            'bespeakid' => $recordData['bespeakid'],
            'aorp' => $recordData['aorp'],
        );
    }
    /**
     * @param $res
     * @return array
     * 根据返回结果获取微信的uid
     */
    public function getUid($res):array {
        $res = $this->decode->decodeFunc($res);
        if($res['result'] != 'ok') {
            return array();
        }
        $uInfo = $this->decode->decodeFunc($res['data']);
        return array(
            'uid' => $uInfo['id'],
        );
    }
    /**
     * @param $res
     * @return array
     * 根据返回结果获取患者id
     */
    public function getPatientId($res):array {
        $res = $this->decode->decodeFunc($res);
        if($res['result'] != 'ok') {
            return array();
        }
        $list = $this->decode->decodeFunc($res['data']);
        foreach ($list as $item) {
            if ($item['name'] == $this->patientName) {
                return array(
                    'sickid' => $item['id'],
                );
            }
        }
        return array();
    }
    /**
     * @param $res
     * @return array
     * 根据返回结果获取可用的问诊时段
     */
    public function getBresPeakId($res):array {
        $res = $this->decode->decodeFunc($res);
        if($res['result'] != 'ok') {
            return array();
        }
        $docList = $this->decode->decodeFunc($res['data']);
        $bespeakid = -1;
        $aorp      = 0;
        //0上午 1下午
        $flag = 0;
        //var_dump($docList);
        foreach ($docList as $item) {
            if ($item['name'] == $this->docName && $item['bdate'] == $this->regDay) {
                if ($item['pm'] != 0 && $item['pm'] != '约满') {
                    //下午有号
                    $aorp      = 1;
                    $flag = 1;
                } else if ($item['am'] != 0 && $item['am'] != '约满') {
                    //上午有号
                    $aorp      = 0;
                    $flag = 1;
                }
                if($flag == 1) {
                    $bespeakid = (int)($item['id']);
                    var_dump('选择医生为',$item);
                    break;
                }
            }
        }
        if($bespeakid != -1) {
            return array(
                'bespeakid' => $bespeakid,
                'aorp' => $aorp,
            );
        }
        return array();
    }
    /**
     * @param $res
     * @return array
     * 根据返回结果判断注册是否成功
     */
    public function getRegistRes($res):array {
        $res = $this->decode->decodeFunc($res);
        var_dump($res);
        if($res['result'] != 'ok') {
            return array();
        }
        return array(
            'res' => 'success',
        );
    }
}
class HosiptalFactory {
    public function createHospital($hospitalName,$config,$regDepId,$docName,$patientName,$regDay,$decode) {
        $hospital = null;
        switch ($hospitalName) {
            case 'A': $hospital = new HospitalA($config['A'],$regDepId,$docName,$patientName,$regDay,$decode);
        }
        return $hospital;
    }
}
function main() {
    $config = array(
        'A' => array(//1号配置
            'wxId' => '*',
            'uInfoUrl' => '*',
            'patientListUrl' => '*',
            'bresPeakUrl' => '*',
            'regUrl' => '*',
        ),
    );
    $decode = new Decode();
    $docName     = '*';
    $patientName = '*';
    $regDepId    = (;
    $regDay      = '2021-03-26';
    $hospitalName = 'A';
    //使用工厂模式创建对应医院
    $factory = new HosiptalFactory();
    $hospital = $factory->createHospital($hospitalName,$config,$regDepId,$docName,$patientName,$regDay,$decode);
    $oper = new HospitalOperation($hospital);
    $oper->run();
}
main();
相关文章
|
设计模式 数据库连接 PHP
PHP中的设计模式:提升代码的可维护性与扩展性在软件开发过程中,设计模式是开发者们经常用到的工具之一。它们提供了经过验证的解决方案,可以帮助我们解决常见的软件设计问题。本文将介绍PHP中常用的设计模式,以及如何利用这些模式来提高代码的可维护性和扩展性。我们将从基础的设计模式入手,逐步深入到更复杂的应用场景。通过实际案例分析,读者可以更好地理解如何在PHP开发中应用这些设计模式,从而写出更加高效、灵活和易于维护的代码。
本文探讨了PHP中常用的设计模式及其在实际项目中的应用。内容涵盖设计模式的基本概念、分类和具体使用场景,重点介绍了单例模式、工厂模式和观察者模式等常见模式。通过具体的代码示例,展示了如何在PHP项目中有效利用设计模式来提升代码的可维护性和扩展性。文章还讨论了设计模式的选择原则和注意事项,帮助开发者在不同情境下做出最佳决策。
|
设计模式 算法 数据库连接
PHP中的设计模式:提高代码的可维护性与扩展性本文旨在探讨PHP中常见的设计模式及其应用,帮助开发者编写出更加灵活、可维护和易于扩展的代码。通过深入浅出的解释和实例演示,我们将了解如何使用设计模式解决实际开发中的问题,并提升代码质量。
在软件开发过程中,设计模式是一套经过验证的解决方案模板,用于处理常见的软件设计问题。PHP作为流行的服务器端脚本语言,也有其特定的设计模式应用。本文将重点介绍几种PHP中常用的设计模式,包括单例模式、工厂模式和策略模式,并通过实际代码示例展示它们的具体用法。同时,我们还将讨论如何在实际项目中合理选择和应用这些设计模式,以提升代码的可维护性和扩展性。
405 4
|
监控 Java 编译器
限流、控并发、减GC!一文搞懂Go项目资源优化的正确姿势
本章介绍Go语言项目在构建与部署阶段的性能调优和资源控制策略,涵盖编译优化、程序性能提升、并发与系统资源管理、容器化部署及自动化测试等内容,助力开发者打造高效稳定的生产级应用。
|
存储 安全 算法
Go语言泛型-泛型对代码结构的优化
Go语言自1.18版本引入泛型,极大提升了代码的通用性与可维护性。通过泛型,开发者可以减少重复代码、提高类型安全性,并增强程序的复用性和可读性。本文详细介绍了泛型在数据结构、算法及映射功能中的应用,展示了其在优化代码结构方面的优势。同时,Go编译器对泛型代码进行类型推导,确保运行时性能不受影响。合理使用泛型,有助于构建更加灵活高效的程序。
|
机器学习/深度学习 存储 监控
上网管理监控软件的 Go 语言流量特征识别算法实现与优化
本文探讨基于Go语言的流量特征识别算法,用于上网管理监控软件。核心内容涵盖AC自动机算法原理、实现及优化,通过路径压缩、哈希表存储和节点合并策略提升性能。实验表明,优化后算法内存占用降低30%,匹配速度提升20%。在1000Mbps流量下,CPU利用率低于10%,内存占用约50MB,检测准确率达99.8%。未来可进一步优化高速网络处理能力和融合机器学习技术。
486 10
|
设计模式 算法 搜索推荐
PHP中的设计模式:提高代码可维护性的秘诀
在本文中,我们将探讨PHP设计模式的重要性以及它们如何帮助开发者编写出更加灵活、可维护的代码。我们将介绍几种常见的设计模式,包括单例模式、工厂模式和策略模式,并通过实际示例展示它们在PHP中的应用。最后,我们会讨论何时使用这些设计模式以及在实际项目开发中的最佳实践。
329 28
|
存储 负载均衡 监控
如何利用Go语言的高效性、并发支持、简洁性和跨平台性等优势,通过合理设计架构、实现负载均衡、构建容错机制、建立监控体系、优化数据存储及实施服务治理等步骤,打造稳定可靠的服务架构。
在数字化时代,构建高可靠性服务架构至关重要。本文探讨了如何利用Go语言的高效性、并发支持、简洁性和跨平台性等优势,通过合理设计架构、实现负载均衡、构建容错机制、建立监控体系、优化数据存储及实施服务治理等步骤,打造稳定可靠的服务架构。
690 1
|
安全 Go 开发者
代码之美:Go语言并发编程的优雅实现与案例分析
【10月更文挑战第28天】Go语言自2009年发布以来,凭借简洁的语法、高效的性能和原生的并发支持,赢得了众多开发者的青睐。本文通过两个案例,分别展示了如何使用goroutine和channel实现并发下载网页和构建并发Web服务器,深入探讨了Go语言并发编程的优雅实现。
458 2
|
设计模式 算法 数据库连接
PHP中的设计模式:提高代码的可维护性与扩展性
设计模式在PHP开发中至关重要,如单例模式确保类仅有一个实例并提供全局访问点,适用于管理数据库连接或日志记录。工厂模式封装对象创建过程,降低系统耦合度;策略模式定义算法系列并使其可互换,便于实现不同算法间的切换。合理选择设计模式需基于需求分析,考虑系统架构,并通过测试驱动开发验证有效性,确保团队协作一致性和代码持续优化。设计模式能显著提升代码质量,解决开发中的设计难题。
243 9
|
设计模式 算法 数据库连接
PHP中的设计模式:提高代码的可维护性和扩展性
【10月更文挑战第13天】 本文将探讨PHP中常见的设计模式及其在实际项目中的应用。通过对比传统编程方式,我们将展示设计模式如何有效地提高代码的可维护性和扩展性。无论是单例模式确保类的单一实例,还是观察者模式实现对象间的松耦合,每一种设计模式都为开发者提供了解决特定问题的最佳实践。阅读本文后,读者将能更好地理解和应用这些设计模式,从而提升PHP编程的效率和质量。

热门文章

最新文章