定义
将一个类的接口转换为用户需要的另外一个接口,解决类(对象)之间接口不兼容的问题
类图
代码
基本实例1
// 这是需要被适配的类
class Socket {
output() {
return "220V";
}
}
// 转换插头的 类
abstract class Power {
abstract charge(): string;
}
class PowerAdaptor extends Power {
constructor(public socket: Socket) {
super();
}
charge(): string {
return this.socket.output() + "转换为12v";
}
}
let adaptor = new PowerAdaptor(new Socket());
console.log(adaptor.charge());
axios类应用适配器
使用适配器处理浏览器和服务器端发送请求的统一处理
// 使用适配器模式处理浏览器或者服务端接口请求
let url = require("url");
function axios(config) {
let adaptor = getDefaultAdaptor();
// 兼容浏览器和服务器端
return adaptor(config);
}
function getDefaultAdaptor() {
let adaptor;
// 在浏览器端
if (typeof XMLHttpRequest !== "undefined") {
adaptor = xhrAxios;
} else if (typeof process !== "undefined") {
// 服务器端
adaptor = httpAxios;
}
return adaptor;
}
function xhrAxios(config) {
return new Promise((resolve, reject) => {
let XHR = new XMLHttpRequest();
XHR.open(config.method, config.url, true);
XHR.onreadystatechange = function () {
if (XHR.readyState == 4) {
if (XHR.status == 200) {
resolve(XHR.responseText);
} else {
reject("请求错误");
}
}
};
});
}
function httpAxios(config) {
let http = require("http");
let urlObj = url.parse(config.url);
return new Promise((resolve, reject) => {
const options = {
hostname: urlObj.hostname,
port: urlObj.port,
path: urlObj.path,
method: config.method,
};
let req = http.request(options, (response) => {
let chunks = [];
response.on("data", function (chunk) {
chunks.push(chunk);
});
response.on("end", function () {
let result = Buffer.concat(chunks).toString();
resolve(result);
});
});
req.on("error", function (error) {
reject(error);
});
req.end();
});
}
多维数组扁平化
let treeData = [
{
name: "河南",
key: "henan",
children: [
{ name: "郑州", key: "zhengzhou" },
{ name: "开封", key: "kaifeng" },
{ name: "洛阳", key: "luoyang" },
{
name: "新乡",
key: "xinxiang",
children: [
{ name: "辉县", key: "huixian" },
{ name: "长垣", key: "changyuan" },
{ name: "延津", key: "yanjin" },
],
},
],
},
{
name: "山东",
key: "shandong",
children: [
{ name: "济南", key: "jinan" },
{ name: "青岛", key: "qingdao" },
],
},
];
// 要把该数组对象放在函数外面,这样每次函数迭代是不会清空数组
let arrData = [];
function flattenData(treeData) {
treeData.forEach((item) => {
arrData.push({ name: item.name, key: item.key });
if (item.children) {
flattenData(item.children, arrData);
}
});
return arrData;
}
function flattenData2(treeData, arr) {
treeData.forEach((item) => {
if (item.children) {
flattenData2(item.children, arr);
}
arr.push({ name: item.name, key: item.key });
});
}
console.log(flattenData(treeData));
let flattenArr = [];
flattenData2(treeData, flattenArr);
console.log(flattenArr);