Assume that a director needs to shoot a movie, actors and photographers are needed, the director calls action, and the staff members take their positions
// 摄影师
class Photographer {
record() {
console.log('start record')
}
}
// 演员
class Actors {
performance() {
console.log('start performance')
}
}
// 导演
class Director {
action() {
console.log('各部门准备,开始!')
const photographer = new Photographer()
const actors = new Actors()
photographer.record()
actors.performance()
}
}
const director = new Director()
director.action()
Now I need to add another gaffer
class LightingEngineer {
openLight() {
console.log('open light')
}
}
class Director {
action() {
console.log('各部门准备,开始!')
const photographer = new Photographer()
const actors = new Actors()
const lightingEngineer = new LightingEngineer()
photographer.record()
actors.performance()
lightingEngineer.openLight()
}
}
const director = new Director()
director.action()
#####I need to add props, sound, assistant director, etc., and then the director is exhausted
#####Because every time the director calls out to start, he must assign different tasks to the staff, which is very easy to make mistakes, the director Tiredness is also inevitable.
#####In the actual scene, the director shouted "Workers and everyone, action!" Everyone started their own work. #####Trained staff will know what they need to do when the director calls action , so how should we modify the code?
#####Add your own action method to each person
class Photographer { record() { console.log('start record') } action() { this.record() } } class Actors { performance() { console .log('start performance') } action() { this.performance() } } class LightingEngineer { openLight() { console.log('open light') } action() { this.openLight() } }
// 将工作人员实例当作参数传入action 方法
class Director {
action(members) {
members.map(member => {
member.action()
})
}
cut(){
console.log('cut')
}
}
const director = new Director()
const photographer = new Photographer()
const actors = new Actors()
const lightingEngineer = new LightingEngineer()
director.action([photographer, actors, lightingEngineer])
director.cut()
director.action([photographer, actors])