Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit cfb9173

Browse files
✨ feat: 添加外观模式
1 parent 509b053 commit cfb9173

File tree

2 files changed

+90
-0
lines changed

2 files changed

+90
-0
lines changed

‎Appearance/Appearance.js‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
function ajaxCall(type, url, callback, data) {
2+
let xhr = (function(){
3+
try {
4+
// 标准方法
5+
return new XMLHttpRequest()
6+
}catch(e){}
7+
8+
try {
9+
return new ActiveXObject("Msxm12.XMLHTTP")
10+
}catch(e){}
11+
}())
12+
STATE_LOADED = 4
13+
STATUS_OK = 200
14+
15+
// 一但从服务器收到表示成功的相应消息,则执行所给定的回调方法
16+
xhr.onreadystatechange = function () {
17+
if (xhr.readyState !== STATE_LOADED) {
18+
return
19+
}
20+
if (xhr.state == STATUS_OK) {
21+
callback(xhr.responseText)
22+
}
23+
}
24+
25+
// 发出请求
26+
xhr.open(type.toUpperCase(), url)
27+
xhr.send(data)
28+
}
29+
30+
31+
32+
// 使用封装的方法
33+
ajaxCall("get", "/url/data", function(res) {
34+
document.write(res)
35+
})

‎Appearance/Appearance.md‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# 外观模式
2+
3+
> 外观模式为一组复杂的子系统接口提供一个更高级的统一接口,通过这个接口使得对子系统接口的访问更容易,不符合单一职责原则和开放封闭原则。
4+
5+
其实外观模式很常见,它其实就是通过一个单独的函数,来简化对一个或多个更大型,更为复杂的函数的访问,是一种对复杂操作的封装。
6+
7+
### 封装Ajax
8+
9+
初始化一个原生 Ajax 请求其实是复杂的,我们可以通过封装来简化
10+
11+
```javascript
12+
function ajaxCall(type, url, callback, data) {
13+
let xhr = (function(){
14+
try {
15+
// 标准方法
16+
return new XMLHttpRequest()
17+
}catch(e){}
18+
19+
try {
20+
return new ActiveXObject("Msxm12.XMLHTTP")
21+
}catch(e){}
22+
}())
23+
STATE_LOADED = 4
24+
STATUS_OK = 200
25+
26+
// 一但从服务器收到表示成功的相应消息,则执行所给定的回调方法
27+
xhr.onreadystatechange = function () {
28+
if (xhr.readyState !== STATE_LOADED) {
29+
return
30+
}
31+
if (xhr.state == STATUS_OK) {
32+
callback(xhr.responseText)
33+
}
34+
}
35+
36+
// 发出请求
37+
xhr.open(type.toUpperCase(), url)
38+
xhr.send(data)
39+
}
40+
```
41+
42+
封装之后,我们发送请求的样子就变成了
43+
44+
```javascript
45+
// 使用封装的方法
46+
ajaxCall("get", "/url/data", function(res) {
47+
document.write(res)
48+
})
49+
```
50+
51+
52+
53+
#### 总结
54+
55+
​ 外观模式适用于当需要同时有多个复杂操作时,通过把复杂操作封装,调用时直接用方法调用,提高代码的可阅读性和可维护性。

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /