工廠模式(Factory pattern)
解決了創(chuàng)建多個相似對象的問題下面,但卻沒有體現(xiàn)對象類型
function createPerson(name, age, job) {
let o = {}
o.name = name
o.age = age
o.job = job
o.sayName = function () {
console.log(name)
}
return o
}
var person1 = createPerson('mamba', 24, 'Software Engineer')
var person2 = createPerson('hui', 20, 'Doctor')
構(gòu)造函數(shù)模式(Constructor pattern)
function Person(name, age) {
this.name = name
this.age = age
}
Person.prototype.sayName = function () {
console.log(this.name)
}
let person1 = new Person('mamba', 24)
混合模式(Mixin pattern)
function object(o) {
function F() {}
F.prototype = o
return new F()
}
function inheritPrototype(subType, superType) {
var prototype = superType.prototype
prototype.constructor = subType
subType.prototype = prototype
}
function Person(name, age) {
this.name = name
this.age = age
}
Person.prototype.sayName = function () {
console.log(this.name)
}
function Student(name, age, score) {
Person.call(this, name, age)
this.score = score
}
inheritPrototype(Student, Person)
Student.prototype.sayScore = function () {
console.log(this.score)
}
模塊模式與單例模式(module and singleton)
單例就是保證一個類只有一個實例后添,實現(xiàn)的方法一般是先判斷實例存在與否器瘪,如果存在直接返回奈揍,如果不存在就創(chuàng)建了再返回,這就確保了一個類只有一個實例對象。
在JavaScript里今野,實現(xiàn)單例的方式有很多種,其中最簡單的一個方式是使用對象字面量的方法罐农,其字面量里可以包含大量的屬性和方法:
var mySingleton = {
property1: "something",
property2: "something else",
method1: function () {
console.log('hello world');
}
};
如果以后要擴展該對象条霜,你可以添加自己的私有成員和方法,然后使用閉包在其內(nèi)部封裝這些變量和函數(shù)聲明涵亏。只暴露你想暴露的public成員和方法宰睡,這就是模塊模式,樣例代碼如下:
var mySingleton = (function () {
/* 這里聲明私有變量和方法 */
var privateVariable = 'something private';
function showPrivate() {
console.log(privateVariable);
}
/* 公有變量和方法(可以訪問私有變量和方法) */
return {
publicMethod: function () {
showPrivate();
},
publicVar: 'the public can see this!'
};
})();
繼續(xù)對單利進(jìn)行改進(jìn)气筋,我們想做到只有在使用的時候才初始化拆内,那該如何做呢?如下:
let singleton = (function () {
let instance
function init(name) {
/*這里定義單例代碼裆悄,定義私有成員*/
let prefixer = 'mamba-'
return {
/*這里定義共有成員*/
getName: function () {
console.log(prefixer + name)
}
}
}
return {
getInstance: function (name) {
if(!instance) {
instance = init(name)
}
return instance
}
}
})()
singleton.getInstance('hui').getName() // mamba-hui
singleton.getInstance('he').getName() // mamba-hui
發(fā)布訂閱模式(Publish/Subscribe Pattern)
function EventTarget() {
this.handlers = {}
}
EventTarget.prototype = {
constructor: EventTarget,
//添加事件
addHandler: function (type, handler) {
this.handlers[type] = this.handlers[type] || []
this.handlers[type].push(handler)
},
//觸發(fā)事件
fire: function (event) {
if (Array.isArray(this.handlers[event.type])) {
let handlers = this.handlers[event.type]
handlers.forEach((handle) => {
console.log(this)
handle.call(this, event)
})
}
},
// 取消訂閱
removeHandler: function (type, handler) {
if (Array.isArray(this.handlers[type])) {
let handlers = this.handlers[type]
for (let i = 0; i < handlers.length; i++) {
if (handlers[i] === handler) {
handlers.splice(i, 1)
break
}
}
}
}
}
let eventObj = new EventTarget()
let handler = () => {
console.dir('何文會是哈哈哈哈')
}
eventObj.addHandler('alert', handler)
eventObj.fire({type: 'alert'})
eventObj.fire({type: 'alert'})
eventObj.removeHandler('alert', handler)
eventObj.fire({type: 'alert'})
// 事件繼承
let object = function (o) {
function F() {}
F.prototype = o
return new F()
}
let inheritPrototype = function (subType, superType) {
let protopype = object(superType.prototype)
protopype.constructor = subType
subType.prototype = protopype
}
function Person(name, age) {
EventTarget.call(this)
this.name = name
this.age = age
}
inheritPrototype(Person, EventTarget)
Person.prototype.say = function (message) {
this.fire({
type: 'message',
message: message
})
}
let handMessage = function (event) {
console.dir(this.name + 'say: ' + event.message)
}
let person = new Person('yhlp', 29)
person.addHandler('message', handMessage)
person.say('Hi, there')
使用發(fā)布訂閱模式寫一個事件管理器
let Event = (function () {
let events = {}
function on(type, handle) {
events[type] = events[type] || []
events[type].push(handle)
}
function fire(type, ...args) {
if(Array.isArray(events[type])) {
events[type].forEach((item) => {
item.apply(this, args)
})
}
}
function off(type) {
events[type] && delete events[type]
}
return {
on: on,
fire: fire,
off: off
}
})()
Event.on('change', function(val){
console.log('change... now val is ' + val);
});
Event.fire('change', '饑人谷');
Event.off('changer');
1
1
1
1
1
1
1
1
1
1