SOLID 五大设计原则
1. SRP 单一职责原则(The Single Responsibility Principle)
- 一个程序只做好一件事
- 如果功能过于复杂就开分开,每个部分保持独立
2. OCP 开放封闭原则(The Open Closed Principle)
- 对拓展开放,对修改封闭
- 增加需求时,拓展新代码,而非修改已有代码
- 软件设计的终极目标
3. LSP 里氏置换原则(The Liskov Substitution Principle)
- 子类能覆盖父类
- 父类能出现的地方子类就能出现
- JS 中使用较少(弱类型&继承使用较少)
4. ISP 接口独立原则(The Interface Segregation Principle)
- 保持接口的单一独立,避免出现“胖接口”
- JS 中没有接口(typescript 除外), 使用较少
- 类似于单一职责原则,这里更关注接口
5. DIP 依赖倒置原则(The Dependency Inversion Principle)
- 保持接口的单一独立,避免出现“胖接口”
- JS 中没有接口(typescript 除外), 使用较少
- 类似于单一职责原则,这里更关注接口
promise 说明 SO
-
S:每个
then
中的逻辑只做一件事 -
O:如果要新增需求,扩展
then
function loadImg(src) { let promise = new Promise(function(resolve, reject) { let img = document.createElement('img') img.onload = function() { resolve(img) } img.onerror = function() { reject('图片加载失败') } img.src = src }) return promise } let src = '//img.mukewang.com/5bc45ce20001976409360316.jpg' let result = loadImg(src) result .then(function(img) { alert(`width:${img.width}`) }) .then(function(img) { alert(`height:${img.height}`) }) .catch(function(ex) { alert(ex) })