JavaScript 组合模式的实现

组合模式指的是,每个面向对象效果,在开启的时候,都需要先实例化对象,然后调用实例化对象初始化方法开启。有多个实例对象,我们就需要实例化多次并调用多次初始化方法。
如果将初始化方法比作是一个开灯的开关,我们就可以将多个开关组成一个组合开关,只要开启组合开关就让所有开关都开启。组合模式就是要制作这样一个组合开关。 

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值