- S(single)-单一职责原则- 一个程序只做好一件事;如果功能过于复杂就拆分开,每个部分保持独立;
- O(open-close)-开放封闭原则- 对扩展开放,对修改封闭;增加需求时,扩展新代码,而非修改已有代码;
- L(Liskov)-里氏置换原则-子类能覆盖父类;父类能出现的地方子类就能出现;
- I(Interface)-接口独立原则-保持接口的单一独立,避免出现”胖接口“;js中没有接口(typescript除外),使用少;
- D(Dependence)-依赖倒置原则-编程依赖抽象接口,不要依赖具体实现;使用方只关注接口而不关注具体类的实现;
1.单一职责原则
一个方法负责一项职责,只能有一项引起函数变化的原因
当一个函数用来处理多个事件时,我们需要对其进行分离,便于增加函数的可读性,方便对函数进行扩充。例如:当我们异步加载图片时
// 单一职责原则:
// const fs = require('fs')
class Joyral {
constructor() {
this.entries = {}
}
addEvent(text) {
let count = ++Joyral.count
let entry = `${count}:${text}`
this.entries[count] = entry
return count
}
removeEntry(index) {
delete this.entries[index]
}
toObject() {
return this.entries
}
}
Joyral.count = 0
let joyral = new Joyral()
joyral.addEvent('今天早上吃了面条')
joyral.addEvent('今天中午吃了米饭')
console.log(joyral.toObject())
2.开放封闭原则
思想:当需要改变一个程序的功能或者给这个程序增加新功能的时候,可以使用增加代码的方式,但是不允许改动程序的源代码。
let Color = Object.freeze({
red: 'red',
green: 'green',
blue: 'blue'
})
let Size = Object.freeze({
small: 'small',
medium: 'medium',
large: 'large'
})
class Product {
constructor(name, color, size) {
this.name = name
this.color = color
this.size = size
}
}
class ProductFilter {
filterBycolor(products, color) {
return products.filter((p) => p.color === color)
}
filterBySize(products, size) {
return products.filter((p) => p.color === size)
}
filterBySizeAndColor(products, size, color) {
return products.filter((p) => p.size === size && p.color === color)
}
// 如果还有不同的功能需要挨个添加
}
// 颜色规格
class ColorSpecification {
constructor(color) {
this.color = color
}
isSatisfied(item) {
return item.color === this.color
}
}
// 尺寸规格
class SizeSpecifcation {
constructor(size) {
this.size = size
}
isSatisfied(item) {
return item.size === this.size
}
}
class AndSpecification {
constructor(...specs) {
this.specs = specs
}
isSatisfied(item) {
return this.specs.every((x) => x.isSatisfied(item))
}
}
let apple = new Product('Apple', Color.green, Size.small)
let tree = new Product('Tree', Color.green, Size.large)
let house = new Product('House', Color.blue, Size.large)
let products = [apple, tree, house]
let pf = new ProductFilter()
console.log('绿色的产品有(老):')
for (let p of pf.filterBycolor(products, Color.green)) {
console.log(`${p.name}是绿色的`)
}
class BetterFilter {
filter(items, spec) {
return items.filter((x) => spec.isSatisfied(x))
}
}
let bf = new BetterFilter()
console.log('绿色的产品有(新):')
for (let p of bf.filter(products, new ColorSpecification(Color.green))) {
console.log(`${p.name} 是绿色的`)
}
console.log('既大又绿的产品:')
let spec = new AndSpecification(new ColorSpecification(Color.green), new SizeSpecifcation(Size.large))
for (let p of bf.filter(products, spec)) {
console.log(`${p.name} 是大的还是绿色的`)
}