1、工厂模式
Creator就像一个工厂一样 , 生成一个个Product实例
/*
* 将new操作单独封装
* 遇到new时、就要考虑是否使用工厂模式
*/
class Product {
constructor (name) {
this.name = name
}
fn1 () {
}
}
class Creator {
create (name) {
return new Product(name)
}
}
const creater = new Creator()
const p = creater.create('terry')
console.log(p)
应用场景:
1、 JQuery --- $('div')
class JQuery {
constructor(selector) {
const ele = Array.prototype.slice.call(document.querySelectorAll(selector))
const len = ele.length
for (let i = 0; i < len; i++) {
this[i] = ele[i]
}
this.selector = selector
this.length = len
}
html() {
}
css(data) {
}
// ...
}
window.$ = function (selector) {
return new JQuery(selector)
}
2、React.createElement()
// React.createElement("div", null)
class Vnode {
...
}
React.createElement = function(tag, attrs, children) {
return new Vnode(tag, attrs, children)
}
3、 Vue异步组件
单例模式
系统中被唯一使用的; 一个类只有一个实例;
// 模拟
class SingleObject {
login() {
console.log('login')
}
}
// 静态方法
SingleObject.getInstance = (function() {
let instance
return function() {
if (!instance) {
instance = new SingleObject()
}
return instance
}
})()
/**
* 什么叫单例模式, 每次获取的都是同一个东西
*/
let obj1 = SingleObject.getInstance()
obj1.login()
let obj2 = SingleObject.getInstance()
obj2.login()
console.log('obj1 === obj2', obj1 === obj2) // obj1 === obj2 true 【什么叫单例模式, 每次获取的都是同一个东西】
装饰器模式
观察者模式/发布订阅模式
代理模式