js設計模式: 工廠模式

一.介紹

工廠模式主要出現在面向對象創建實例的過程中,其本質是爲了更方便生成實例,因此

在遇到使用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

當我們在使用(div),jquery,newJquery(div),('div')的時候,直接返回的是一個jquery實例,而不是需要new Jquery('div')才能夠返回,()實際上做了類似下列的事情.

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)
})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章