作用:
可以将复杂的类进行一些拆分,让抽象和实现进行分离解耦,可以让每一个部分都可以单独维护
方便扩展和维护
示例:
javascript
class Obj {
constructor(person) {
this.person = person
this.name = person.name
}
getHobby(){
return this.person.hobby
}
getBehavior(){
return this.person.behavior()
}
}
class Human {
constructor(hobby) {
this.name = '打工人'
this.hobby = hobby
}
behavior() {
console.log('一身打工人的怨气')
}
}
class Deity {
constructor(hobby) {
this.name = '神仙'
this.hobby = hobby
}
behavior() {
console.log('过着神仙般的生活')
}
}
const wjt = new Obj(new Human('抖音刷美女,或者打游戏'))
const sunwukong = new Obj(new Deity('定身七仙女,然后吃桃子'))
console.log(wjt.name+'的爱好:'+wjt.getHobby())
console.log(sunwukong.name+'的爱好:'+sunwukong.getHobby())