工厂模式(Factory pattern)
解决了创建多个相似对象的问题,但却没有体现对象类型
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')
构造函数模式(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)
单例就是保证一个类只有一个实例,实现的方法一般是先判断实例存在与否,如果存在直接返回,如果不存在就创建了再返回,这就确保了一个类只有一个实例对象。
在JavaScript里,实现单例的方式有很多种,其中最简单的一个方式是使用对象字面量的方法,其字面量里可以包含大量的属性和方法:
var mySingleton = {
property1: "something",
property2: "something else",
method1: function () {
console.log('hello world');
}
};
如果以后要扩展该对象,你可以添加自己的私有成员和方法,然后使用闭包在其内部封装这些变量和函数声明。只暴露你想暴露的public成员和方法,这就是模块模式,样例代码如下:
var mySingleton = (function () {
/* 这里声明私有变量和方法 */
var privateVariable = 'something private';
function showPrivate() {
console.log(privateVariable);
}
/* 公有变量和方法(可以访问私有变量和方法) */
return {
publicMethod: function () {
showPrivate();
},
publicVar: 'the public can see this!'
};
})();
继续对单利进行改进,我们想做到只有在使用的时候才初始化,那该如何做呢?如下:
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
发布订阅模式(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)
},
//触发事件
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')
使用发布订阅模式写一个事件管理器
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