什么是面向?qū)ο?/h2>
把客觀的對(duì)象抽象成屬性數(shù)據(jù)和對(duì)數(shù)據(jù)的相關(guān)的操作(也就是方法)荐吉,把內(nèi)部的細(xì)節(jié)和不想關(guān)的信息隱藏起來鸵荠,把同一個(gè)類型的客觀對(duì)象的屬性數(shù)據(jù)和操作綁定在一起威创,封裝成類诫龙,并且允許分成不同層次進(jìn)行抽象析显,通過繼承實(shí)現(xiàn)屬性和操作的共享。
- 面向?qū)ο蟮姆治?OOA
- 面向?qū)ο蟮脑O(shè)計(jì) OOD
- 面向?qū)ο蟮木幊?OOP
繼承
/**
* 類 對(duì)象(實(shí)例)
* 父類 Animal 是公共的
*/
class Animal {
constructor(name) {
this.name = name
}
eat() {
console.log(`${this.name} eat`)
}
}
let animal = new Animal('動(dòng)物')
animal.eat()
/**
* 繼承
* 子類繼承父類
* 繼承可以把公共方法抽離出來签赃,減少冗余
*/
class Cat extends Animal {
constructor(myName, age) {
super(myName)
this.age = age
}
speak() {
console.log(`${this.name}: 喵喵~~`)
}
}
let cat = new Cat('小花貓', 2)
cat.eat()
cat.speak()
封裝
把數(shù)據(jù)封裝起來谷异,減少耦合,不該外部訪問的不要讓外部訪問锦聊,利于數(shù)據(jù)的接口權(quán)限管理 ES6 目前不支持歹嘹,一般認(rèn)為_開頭的都會(huì)私有的,不要使用孔庭,后面講的會(huì)使用 ts
class person {
public name // 公共的尺上,類或者類外都可以訪問材蛛,比如:你的名字誰都可以知道
protected age // 受保護(hù)的自己和自己的子類可以訪問,比如:女性的年齡
private monney // 只有自己可以知道哦怎抛,私房錢
constructor(name, age, monney) {
this.name = name
this.age = age
this.monney = monney
}
getName() {
console.log(this.name)
}
getAge() {
console.log(this.age)
}
getMonney() {
console.log(this.monney) // [ts] 屬性 monney 為私有屬性卑吭,只能在類 Person 中訪問
}
}
let person = new person('jack', 20, '10000')
多態(tài)
同一個(gè)接口可以不同實(shí)現(xiàn),保持子類的開發(fā)性和靈活性马绝,面向接口編程
class Animal {
public name
protected age
private weight
constructor(name, age, weight) {
this.name = name
this.age = age
this.weight = weight
}
}
class Person extends Animal {
private monney
constructor(name, age, weight, monney) {
super(name, age, weight)
this.monney = monney
}
speak() {
console.log('hi hi')
}
}
class Dog extends Animal {
private monney
constructor(name, age, weight) {
super(name, age, weight)
}
speak() {
console.log('汪汪~~')
}
}
let p = new Person('jack', 10, 10, 10)
p.speak()
let d = new Dog('rose', 10, 10)
d.speak()
設(shè)計(jì)原則
單一職責(zé)原則
- 一個(gè)程序只做好一件事
- 如果功能特別復(fù)雜就拆分
開放封閉原則
- 對(duì)擴(kuò)展開放豆赏,對(duì)修改關(guān)閉
- 增加需求時(shí),擴(kuò)展新代碼迹淌,而非修改已有代碼
- 這是軟件設(shè)計(jì)的終極目標(biāo)
function parseJSON() {
return response.json()
}
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response
}
const error = new Error(response.statusText)
error.response = response
throw error
}
export default function requset(url, options) {
return fetch(url, options)
.then(checkStatus)
.then(parseJSON)
.then(data => data)
.catch(err => ({ err }))
}
其他原則
- 里氏替換原則
- 接口隔離原則
- 依賴倒置原則