| 设计模式 | - 适配器模式
适配器模式
• 将一个接口转换为另一个接口以供给用户有效使用。
class Socket {
output() {
return '输出220V';
}
}
abstract class Power {
abstract charge(): string;
}
class PowerAdapter extends Power {
constructor(public socket: Socket) {
super();
}
//转换后的接口和转换前不一样
charge() {
return this.socket.output() + ' 经过转换 输出24V';
}
}
let powerAdapter = new PowerAdapter(new Socket());
console.log(powerAdapter.charge());
参数适配
function F(obj) {
const adapter = {
name: "ryan",
age: 18,
work: "coder",
};
adapter.name = obj.name || adapter.name;
}
数据适配
const arr = ["javascript", "2021-9-12", "《你不知道的js》"];
const adapterObj = {
name: arr[0],
time: arr[1],
book: arr[2],
};
function getDefaultAdapter(): any {
var adapter;
if (typeof XMLHttpRequest !== 'undefined') {
adapter = xhr;
} else if (typeof process !== 'undefined') {
adapter = http;
}
return adapter;
}
6.2.5 tree (一维转多维,多维转一维)
- 树型结构数据在下拉框中显示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<select id="users"></select>
<script>
let tree = [{
name: '父亲',
key: '1',
children: [
{
name: '儿子',
key: '1-1',
children: [
{
name: '孙子',
key: '1-1-1'
}
]
}
]
}]
function flattenAdapter(tree, flattenArray) {
tree.forEach((item) => {
if (item.children) {
flattenAdapter(item.children, flattenArray)
}
flattenArray.push({ name: item.name, key: item.key })
})
return flattenArray
}
let array = [];
flattenAdapter(tree, array);
array.reverse();
let users = document.getElementById('users');
let options = array.map(item => `<option value="${item.key}">${item.name}</option>`).join('');
users.innerHTML = options;
</script>
</body>
</html>
转载自:https://juejin.cn/post/7200306886344015930