组合模式指的是,每个面向对象效果,在开启的时候,都需要先实例化对象,然后调用实例化对象初始化方法开启。有多个实例对象,我们就需要实例化多次并调用多次初始化方法。
如果将初始化方法比作是一个开灯的开关,我们就可以将多个开关组成一个组合开关,只要开启组合开关就让所有开关都开启。组合模式就是要制作这样一个组合开关。
class Carousel{
init() {
console.log('这是轮播图的初始化方法')
}
}
class Tab{
init() {
console.log('这是tab切换的初始化方法')
}
}
class Enlarge{
init() {
console.log('这是放大镜的初始化方法')
}
}
如何将这3个效果的初始化方法调用作为一个组合开关?
思路:既然要组合,就需要将这3个单独的开关组合在一起。将这个3个类的实例化对象,都放在同一个容器中,遍历容器中的每个效果对象,调用初始化方法:
class Combination{
// 定义属性container作为效果对象存放的容器
container = []
// 将效果对象放在容器中的方法
add(...arr) {
if(!arr.length) return
this.container = this.container.concat(arr)
}
// 组合开关
init() {
// 遍历容器
this.container.forEach(item => {
// 批量调用
item.init()
})
}
}
var c = new Combination()
c.add(new Tab, new Carousel, new Enlarge)
c.init()
如果效果对象的初始化不叫init,如何更加灵活的做组合开关呢?
class Carousel{
init() {
console.log('这是轮播图的初始化方法')
}
}
class Tab{
start() {
console.log('这是tab切换的初始化方法')
}
}
class Enlarge{
go() {
console.log('这是放大镜的初始化方法')
}
}
class Combination{
// 定义属性container作为效果对象存放的容器
container = []
// 将效果对象放在容器中的方法
add(...arr) {
if(!arr.length) return
this.container = this.container.concat(arr)
}
// 组合开关
init() {
// 遍历容器
this.container.forEach(item => {
// 批量调用
for(var key in item) {
item[key][key]()
}
})
}
}
var c = new Combination()
c.add({init: new Tab}, {start: new Carousel}, {go: new Enlarge})
c.init()