用23种设计模式打造一个cocos creator的游戏框架----(八)适配器模式

1、模式标准

模式名称:适配器模式

模式分类:结构型

模式意图:适配器模式的意图是将一个类的接口转换成客户端期望的另一个接口。适配器模式使原本接口不兼容的类可以一起工作。

结构图:

适用于:

  1. 系统需要使用现有的类,而这些类的接口不符合系统的需要。 适配器可以在不修改现有类的情况下提供一个兼容的接口。

  2. 想要构建一个可重用的类,这个类可以与其他不相关的类或不可预见的类(即那些接口可能不一定兼容的类)协同工作。

  3. 需要一个统一的输出接口,而输入端的类型不可预知

2、分析与设计

需要统一输出接口,在游戏开发中应该也有一些,这里举的例子是通讯适配。比如一般的网络请求都是XMLHttpRequest进行的get与post的请求,请求体是json,返回的是自己熟悉的{code:200,msg:"成功",data:{}}格式,但是我用tsrpc这个ts框架后,请求体变成了tsrpc特有的Proto,且返回个格式变为了{isSucc:true,err:null,res:{}},我希望游戏框架里面请求方式是类似xhgame.net.post('/api/userInfo'),无论我们如何换后端,前端都是不用改。

3、开始打造

TypeScript 复制代码
export abstract class IRequest {
    abstract get(url: string, reqData: any, callback: Function): void
    abstract post(url: string, reqData: any, callback: Function): void
}
TypeScript 复制代码
export class Http extends IRequest {

    public get(url: string, reqData: any, callback: Function) {
        url = xhgame.config.game_host + url
        url += "?";
        for (var item in reqData) {
            url += item + "=" + reqData[item] + "&";
        }
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status >= 200 && xhr.status < 400) {
                    var response = xhr.responseText;
                    if (response) {
                        var responseJson = JSON.parse(response);
                        callback(responseJson);
                    } else {
                        console.log("返回数据不存在")
                        callback(false);
                    }
                } else {
                    console.log("请求失败")
                    callback(false);
                }
            }
        };
        xhr.open("GET", url, true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.setRequestHeader('Authorization', 'Bearer ' + xhgame.storage.origin_get('token'));
        xhr.send();
    }


    public post(url: string, reqData: any, callback: Function) {
        url = xhgame.config.game_host + url
        //1.拼接请求参数
        var param = "";
        for (var item in reqData) {
            param += item + "=" + reqData[item] + "&";
        }
        //2.发起请求
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status >= 200 && xhr.status < 400) {
                    var response = xhr.responseText;
                    if (response) {
                        var responseJson = JSON.parse(response);
                        callback(responseJson);
                    } else {
                        console.log("返回数据不存在")
                        callback(false);
                    }
                } else {
                    console.log("请求失败")
                    callback(false);
                }
            }
        };
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.setRequestHeader('Authorization', 'Bearer ' + xhgame.storage.origin_get('token'));
        xhr.send(param);//reqData为字符串形式: "key=value"
    }
}
TypeScript 复制代码
import { Http } from "../../../xhgame-framework/net/Http";
import { HttpClient as HttpClient_Miniapp, WsClient as WsClient_Miniapp } from 'tsrpc-miniapp';
import { HttpClient as HttpClient_Browser, WsClient as WsClient_Browser } from 'tsrpc-browser';
import { serviceProto as ServiceProtoGate, ServiceType as ServiceTypeGate } from "../../tsshared/protocols/ServiceProtoGate";

import { PREVIEW } from "cc/env";

export enum TSPRC_API {
    GetOpenid = "GetOpenid"
}
// 设计模式6(适配器)
export class TsrpcAdapterHttp extends Http {
    tsrpc: HttpClient_Miniapp<ServiceTypeGate> | HttpClient_Browser<ServiceTypeGate> = null

    constructor() {
        super()
        this.tsrpc = new (PREVIEW ? HttpClient_Browser : HttpClient_Miniapp)(ServiceProtoGate, {
            server: 'http://127.0.0.1:8010',
            json: true,
            logger: console,
        });
    }

    async get(url: TSPRC_API, reqData: any, callback: Function) {
        let res = await this.tsrpc.callApi(url, reqData)
        callback(res)
    }

    async post(url: TSPRC_API, reqData: any, callback: Function) {
        let res = await this.tsrpc.callApi(url, reqData)
        callback(res)
    }

}

4、开始使用

在用构建器构建游戏时

TypeScript 复制代码
    setNet(): IGameBuilder {
        //return new Http()
        this.net = new TsrpcAdapterHttp()
        return this;
    }

有了适配器请求方式都统一称如下方式了

TypeScript 复制代码
xhgame.net.post(api,data)

完成

相关推荐
游了个戏41 分钟前
用AI做了个小游戏(二)
人工智能·游戏·微信
回忆2012初秋11 小时前
工厂方法模式完整实现:GPS转换
设计模式·工厂方法模式
glimix12 小时前
Word-Pop:使用C语言开发打单词游戏
c语言·游戏
胡志辉的博客14 小时前
多智能体协作,不是多开几个 Agent:从中介者模式看 OpenClaw 和 Hermes Agent
人工智能·设计模式·ai·agent·中介者模式·openclaw·herman
shark222222214 小时前
能懂!基于Springboot的用户增删查改(三层设计模式)
spring boot·后端·设计模式
014-code15 小时前
日志规范:怎么写才不算写废话
java·开发语言·设计模式·日志
上海云盾-小余16 小时前
DDoS 攻击应急响应全流程:从告警触发到业务恢复的黄金 15 分钟
服务器·安全·游戏·ddos
楼田莉子16 小时前
同步/异步日志系统:日志落地模块\日志器模块\异步日志模块
linux·服务器·c++·学习·设计模式
ximagine18 小时前
【26年4月外设鼠标推荐清单】教父级游戏鼠标选购指南!18款鼠标从竞技上分到拯救鼠标手!
科技·游戏·计算机外设·智能路由器·鼠标·ximagine
游了个戏20 小时前
我用AI做了个小游戏(一)
人工智能·游戏·微信