应该避免多层继承,可以将一些简单的对象组合成新的对象。
const canEat = {
eat: function() {
this.hunger--
console.log('eatting')
}
}
const canWalk = {
walk: function() {
console.log('walking')
}
}
function Person() {
}
Object.assign(Person.prototype, canEat, canWalk)
const p = new Person()
console.log(p)

- 不同行为对象组合不同对象
const canEat = {
eat: function() {
this.hunger--
console.log('eatting')
}
}
const canWalk = {
walk: function() {
console.log('walking')
}
}
const canSwim = {
swim: function() {
console.log('swim')
}
}
function Person() {
}
Object.assign(Person.prototype, canEat, canWalk)
const p = new Person()
console.log(p)
function Goldfish() {}
Object.assign(Goldfish.prototype, canEat, canSwim)
const goldfish = new Goldfish()
console.log(goldfish)

- 使用mixin
function mixin(target, ...sources) {
Object.assign(target, ...sources)
}
const canEat = {
eat: function() {
this.hunger--
console.log('eatting')
}
}
const canWalk = {
walk: function() {
console.log('walking')
}
}
const canSwim = {
swim: function() {
console.log('swim')
}
}
function Person() {
}
mixin(Person.prototype, canEat, canWalk)
const p = new Person()
console.log(p)
function Goldfish() {}
mixin(Goldfish.prototype, canEat, canSwim)
const goldfish = new Goldfish()
console.log(goldfish)

本文探讨了软件设计中组合模式的应用,通过将不同的行为对象如进食、行走和游泳组合到Person和Goldfish对象中,展示了如何避免多层继承的复杂性,提供了一种更灵活的对象行为设计方法。

被折叠的 条评论
为什么被折叠?



