工厂模式
工厂模式是JS
中很常见的一种模式,用来批量创建对象,使用工厂模式可以帮助我们避免创建同类对象时产生冗余代码。下面我们通过一个实例来看看工厂模式在实际开发中的应用。
实例
点击页面上以下按钮
页面依次弹出以下提示信息
代码实现
const ICONS = {
success: './assets/success.png',
warn: './assets/warn.png',
info: './assets/info.png',
fail: './assets/fail.png',
}
let id = 0
// 构造函数显示返回div
function NotificationCreater(options) {
const div = document.createElement('div')
div.style.position = 'fixed'
div.style.height = '30px'
div.style.width = '200px'
div.style.border = "1px solid #eee"
div.style.borderRadius = "3px"
const { type, text } = options;
div.innerHTML = `<img src=${ICONS[type]}> ${text}`
document.body.appendChild(div)
return div
}
// 消息提示框创建函数
const Notification = options => {
// options校验
const {text, type} = options;
if(!type || !text) {
throw new Error('params of optios is illegal')
}
let instace = new NotificationCreater(options)
instace.style.top = (id * 32) + 'px'
id++
}
document.querySelectorAll('button').forEach(btn =>
btn.addEventListener('click', function () {
// Notification({}) //Uncaught Error: params of optios is illegal
Notification({ type: this.getAttribute('type'),
text: this.getAttribute('type') })
}))
基于工厂模式我们创建了生成弹窗的工厂方法,在点击按钮式页面上显示对应弹窗,文章中的代码只是作了最基础的封装,还可以加上弹窗
close
事件。
js
中的建造者模式和工厂模式类似,目的都是为了批量创建对象,建造者模式在创建对象的过程中更为复杂,举个例子, 学生实例基于createStudent
工厂方法创建而来,在createStudent
中调用new Name()
构造函数给实例添加名称,调用new age()
方法给学生实例添加年龄。可以认为建造者模式是工厂模式的一种延伸,只是对象的创建更为复杂。