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();
相关文章
|
2月前
|
Go 数据安全/隐私保护 UED
优化Go语言中的网络连接:设置代理超时参数
优化Go语言中的网络连接:设置代理超时参数
|
3月前
|
存储 负载均衡 监控
如何利用Go语言的高效性、并发支持、简洁性和跨平台性等优势,通过合理设计架构、实现负载均衡、构建容错机制、建立监控体系、优化数据存储及实施服务治理等步骤,打造稳定可靠的服务架构。
在数字化时代,构建高可靠性服务架构至关重要。本文探讨了如何利用Go语言的高效性、并发支持、简洁性和跨平台性等优势,通过合理设计架构、实现负载均衡、构建容错机制、建立监控体系、优化数据存储及实施服务治理等步骤,打造稳定可靠的服务架构。
82 1
|
3月前
|
SQL 监控 算法
为Go应用无侵入地添加任意代码
这篇文章旨在提供技术深度和实践指南,帮助开发者理解并应用这项创新技术来提高Golang应用的监控与服务治理能力。在接下来的部分,我们将通过一些实际案例,进一步展示如何在不同场景中应用这项技术,提供更多实践启示。
|
3月前
|
安全 Go 开发者
代码之美:Go语言并发编程的优雅实现与案例分析
【10月更文挑战第28天】Go语言自2009年发布以来,凭借简洁的语法、高效的性能和原生的并发支持,赢得了众多开发者的青睐。本文通过两个案例,分别展示了如何使用goroutine和channel实现并发下载网页和构建并发Web服务器,深入探讨了Go语言并发编程的优雅实现。
56 2
|
4月前
|
设计模式 算法 数据库连接
PHP中的设计模式:提高代码的可维护性和扩展性
【10月更文挑战第13天】 本文将探讨PHP中常见的设计模式及其在实际项目中的应用。通过对比传统编程方式,我们将展示设计模式如何有效地提高代码的可维护性和扩展性。无论是单例模式确保类的单一实例,还是观察者模式实现对象间的松耦合,每一种设计模式都为开发者提供了解决特定问题的最佳实践。阅读本文后,读者将能更好地理解和应用这些设计模式,从而提升PHP编程的效率和质量。
|
4月前
|
JSON 搜索推荐 Go
ZincSearch搜索引擎中文文档及在Go语言中代码实现
ZincSearch官网及开发文档均为英文,对非英语用户不够友好。GoFly全栈开发社区将官方文档翻译成中文,并增加实战经验和代码,便于新手使用。本文档涵盖ZincSearch在Go语言中的实现,包括封装工具库、操作接口、统一组件调用及业务代码示例。官方文档https://zincsearch-docs.zinc.dev;中文文档https://doc.goflys.cn/docview?id=41。
187 0
|
4月前
|
设计模式 SQL 安全
PHP中的设计模式:单例模式的深入探索与实践在PHP开发领域,设计模式是解决常见问题的高效方案集合。它们不是具体的代码,而是一种编码和设计经验的总结。单例模式作为设计模式中的一种,确保了一个类仅有一个实例,并提供一个全局访问点。本文将深入探讨单例模式的基本概念、实现方式及其在PHP中的应用。
单例模式在PHP中的应用广泛,尤其在处理数据库连接、日志记录等场景时,能显著提高资源利用率和执行效率。本文从单例模式的定义出发,详细解释了其在PHP中的不同实现方法,并探讨了使用单例模式的优势与注意事项。通过对示例代码的分析,读者将能够理解如何在PHP项目中有效应用单例模式。
|
5月前
|
设计模式 算法 PHP
PHP中的设计模式:提升代码的灵活性与可维护性
在本文中,我们将深入探讨PHP编程语言中的一种重要概念——设计模式。设计模式是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。它代表了最佳的实践,被有经验的面向对象的软件开发人员所采用。本文将通过具体的实例,展示如何在PHP项目中应用设计模式,以提高代码的灵活性和可维护性。无论你是PHP初学者还是经验丰富的开发者,都能从中获得有价值的见解。
|
5月前
|
设计模式 存储 数据库连接
探索PHP中的设计模式:提高代码的可维护性与扩展性
本文将深入探讨PHP中常用的设计模式,包括单例模式、工厂模式和观察者模式。通过具体的代码示例,展示如何在实际项目中应用这些设计模式,以提高代码的可维护性与扩展性。无论你是PHP初学者还是有一定经验的开发者,都可以通过本文的学习,提升你的编程技巧和项目架构能力。
|
5月前
|
设计模式 数据库连接 PHP
PHP中的设计模式:提升代码的可维护性与扩展性在软件开发过程中,设计模式是开发者们经常用到的工具之一。它们提供了经过验证的解决方案,可以帮助我们解决常见的软件设计问题。本文将介绍PHP中常用的设计模式,以及如何利用这些模式来提高代码的可维护性和扩展性。我们将从基础的设计模式入手,逐步深入到更复杂的应用场景。通过实际案例分析,读者可以更好地理解如何在PHP开发中应用这些设计模式,从而写出更加高效、灵活和易于维护的代码。
本文探讨了PHP中常用的设计模式及其在实际项目中的应用。内容涵盖设计模式的基本概念、分类和具体使用场景,重点介绍了单例模式、工厂模式和观察者模式等常见模式。通过具体的代码示例,展示了如何在PHP项目中有效利用设计模式来提升代码的可维护性和扩展性。文章还讨论了设计模式的选择原则和注意事项,帮助开发者在不同情境下做出最佳决策。

热门文章

最新文章