工厂方法模式,通过对产品类的抽象,使其创建业务主要用于负责创建多类产品的实例
const Java = function (content) {
this.content = content
;(function () {
let oDiv = document.createElement('div')
oDiv.innerHTML = content
oDiv.style.color = 'green'
document.getElementById('container').appendChild(oDiv)
})()
}
const Php = function (content) {
this.content = content
;(function () {
let oDiv = document.createElement('div')
oDiv.innerHTML = content
oDiv.style.color = 'red'
document.getElementById('container').appendChild(oDiv)
})()
}
const JavaScript = function (content) {
this.content = content
;(function () {
let oDiv = document.createElement('div')
oDiv.innerHTML = content
oDiv.style.color = 'pink'
document.getElementById('container').appendChild(oDiv)
})()
}
简单工厂模式,扩展的话需要改动两个地方,一个是工厂类,一个是具体产品类
function JobFactory(type, content) {
switch (type) {
case 'java':
return new Java(content)
break
case 'javascript':
return new JavaScript(content)
break
}
}
JobFactory('java', 'Java 培训哪家强1111')
安全模式实例
var Demo = function () {}
Demo.prototype.show = function () {
console.log('show')
}
//正常使用
let d1 = new Demo()
d1.show() //show
//非正常使用
// let d2 = Demo()
// d2.show() //报错
//改造上面的 demo
const Demo2 = function () {
// if (this instanceof Demo2) {
// return this
// } else {
// return new Demo2()
// }
console.log('🚀 ~ Demo2 ~ this:', this)
if (!(this instanceof Demo2)) {
console.log('🚀 ~ Demo2 ~ new Demo2():', new Demo2())
return new Demo2()
}
}
Demo2.prototype.show = function () {
console.log('show 999')
}
let d2 = Demo2()
d2.show() //报错
工厂方法模式,扩展的话只需要改动工厂类
const Factory = function (type, content) {
if (this instanceof Factory) {
return new this[type](content)
} else {
return new Factory(type, content)
}
}
Factory.prototype = {
//注意方法这里不能简写需要:function
Java: function (content) {
//注意这里不能加this
this.content = content
console.log('🚀 ~ content11111:', content)
;(function () {
let oDiv = document.createElement('div')
oDiv.innerHTML = content
oDiv.style.color = 'green'
document.getElementById('container').appendChild(oDiv)
})()
},
JavaScript: function (content) {
this.content = content
;(function () {
let oDiv = document.createElement('div')
oDiv.innerHTML = content
oDiv.style.color = 'red'
document.getElementById('container').appendChild(oDiv)
})()
},
UIEvent: function (content) {
this.content = content
;(function () {
let oDiv = document.createElement('div')
oDiv.innerHTML = content
oDiv.style.color = 'pink'
document.getElementById('container').appendChild(oDiv)
})()
},
Php: function (content) {
this.content = content
;(function () {
let oDiv = document.createElement('div')
oDiv.innerHTML = content
oDiv.style.color = 'blue'
document.getElementById('container').appendChild(oDiv)
})()
}
}
实现
const data = [
{
type: 'Java',
content: 'Java 培训哪家强'
},
{
type: 'JavaScript',
content: 'JavaScript 培训哪家强'
},
{
type: 'Php',
content: 'PHP 培训哪家强'
},
{
type: 'UIEvent',
content: 'UIEvent 培训哪家强'
}
]
//创建实例
for (let i = 0; i < data.length; i++) {
Factory(data[i].type, data[i].content)
}