工廠模式
- 將new操作單獨封裝
- 遇到new時,就要考慮該是否使用工廠模式
示例
當你去購買漢堡,直接點餐,取餐,不會自己親手做
商店要“封裝”做漢堡的作業,做好直接賣給買者


class Product {
constructor(name) {
this.name = name
}
init(){
alert('init')
}
fun1(){
alert('fun1')
}
fun2(){
alert('fun2')
}
}
class Creator {
creat(name) {
return new Product()
}
}
// 測驗
let creat = new Creator()
let p = creat.creat('p1')
p.init()
p,fun1()
工廠模式應用場景
jQuery-$('div')
class jQuery {
constructor(selector) {
let slice = Array.prototype.slice
let dom = slice.call(document.querySelectorAll(selector))
let len = dom ? dom.length : 0
for (let i = 0; i < len; i++) {
this[i] = dom[i]
}
this.length = len
this.selector = selector || ''
}
append(node) {
}
addClass(name) {
}
html(data) {
}
// 此處省略若干 API
}
window.$ = function (selector) {
return new jQuery(selector)
}
// 測驗代碼
var $p = $('p')
console.log($p)
console.log($.addClass)
React.createElement
react如何做?
//jsx語法
var profile = <div>
<img src=https://www.cnblogs.com/ygjzs/p/"avatar.png" className="profile" />
{[user.firstName,user.lastName].join('')}</h3>
</div>
/*react手寫dom*/
var profile = React.CreateElement("div",null,
React.CreateElement("img",{src: "avatar.png", className: "profile"}),
React.CreateElement("h3", null,[user.firstName, user.lastName].join(" "))
)
/*react內部代碼*/
class Vnode(tag, attrs, children) {
// ...省略內部代碼...
}
React.CreateElement = function (tag, attrs, children) {
return new Vnode(tag, attrs, children)
}
vue異步組件
Vue.component('asycn-example', function (reslove, reject) {
setTimeout(function() {
reslove({
template: '<div>I am async!</div>'
})
})
})
設計原則驗證
- 建構式和創建者分離
- 符合開飯封閉原則
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/29336.html
標籤:設計模式
上一篇:設計原則
下一篇:JavaScript-單例模式
