一.介紹
工廠模式主要出現在面向對象創建實例的過程中,其本質是爲了更方便生成實例,因此
在遇到使用new時,就要是否要使用工廠模式
二.實現
1.UML類圖
2.代碼實現
class Product {
constructor() {
}
init() {
console.log('init')
}
fn1() {
console.log('fn1')
}
fn2() {
console.log('fn2')
}
}
class Creator {
create(name) {
return new Product(name)
}
}
//測試
let creator = new Creator()
let p = creator.create()
p.init() //init
p.fn1() //fn1
三.場景舉例
- jquery- $(‘div’)
- React.createElement
- vue異步組件
1.jquery
當我們在使用()實際上做了類似下列的事情.
window.$ = function(selector) {
return new JQuery(selector);
}
這樣的好處是:方便生成對象,並且有利於鏈式調用
$('div')
.eq(0)
.css('width', '200px')
.show();
2.React.createElement
class Vnode(tag, attrs, children) {
//..內部省略代碼...
}
React.createElement = function(tag, attrs, children) {
return new Vnode(tag, attrs, children)
}
3.vue異步組件
Vue.component('async-example', function (resolve, reject) {
setTimeout(function () {
resolve({
template: '<div>I am async!</div>'
})
}, 1000)
})