设计模式
结构型模式
1.适配器模式
特点:将一个接口转换成客户希望的另一个接口,使接口不兼容的那些类可以一起工作。其别名为包装器(Wrapper)。适配器模式既可以作为类结构型模式,也可以作为对象结构型模式。
后台返回的数据格式不同,可以通过适配器修改。例:
后台返回json格式的数据,通过方法检索出自己需要的数据进行显示,这个方法即为适配器。
通常用来避免项目迭代后数据格式或者方法名发生改变出现的错误。
最优解:项目开发过程中前后端协商讨论数据格式、文件名等代码规范。
2.代理模式
为一个对象提供一个代用品或占位符,以便控制对他的访问。
在一个对象中调用其他对象的方法(函数可以实例化成对象)
保护代理:数据拦截(可以在函数中条件判断拦截数据从而执行不同下文)
虚拟代理:数据通过这些代理传递没有被拦截(可实现图片懒加载)
3.桥接模式
把事物对象和其具体行为、具体特征分离开来,使它们可以各自独立的变化。
需要一种方式让对象和行为分离,便于随意拼接。
优点:分离抽象接口及其实现部分,提高可拓展性。
缺点:增加系统的理解和设计难度
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
boy,girl,piano,guitar
boy-piano,boy-guitar,girl-piano,girl-guitar
function Boy(instrument) {
this.sayHi = function() {
console.log('hi, 我是男生')
}
this.playInstrument = function() {
instrument.play()
}
}
function Girl(instrument) {
this.sayHi = function() {
console.log('hi, 我是女生')
}
this.playInstrument = function() {
instrument.play()
}
}
function Piano() {
this.play = function() {
console.log('钢琴开始演奏')
}
}
function Guitar() {
this.play = function() {
console.log('吉他开始演奏')
}
}
let piano = new Piano()
let guitar = new Guitar()
let pianoBoy = new Boy(piano)
pianoBoy.playInstrument()
let guitarGirl = new Girl(guitar)
guitarGirl.playInstrument()
1 | boy,girl,piano,guitar |