1. Singleton mode
Only get a single object, through the singleton pattern can ensure that the system, the application of the pattern of a class only one instance has multiple implementations
const ProxyCreateSingleton = (function(fn){
let instance
return function(age){
if(instance) return instance
return instance = new fn(...arguments)
}
})(Per)
function Per(name,age){
this.name = name
this.age = age
}
p=new ProxyCreateSingleton('哦',11)
Copy the code
The factory pattern
The factory pattern is a design pattern used to create objects. Instead of exposing the logic of object creation, we encapsulate the logic in a function that can then be a factory.
Function Factory(opts){let obj={color:opts.color, name:opts.name} obj. GetInfo = function(){return ' '+ obj.name ', color: '+ obj.color '; } return obj; } let phone = new Factory(' phone ',' black ') phone.getinfo ()Copy the code
Subscription publishing model
Supports simple broadcast communication and automatically notifies subscribed objects when the state of the object changes. The subscription mode is very similar to the observer mode, but with an additional middle layer for managing messages (information channels), it can be viewed as an optimized observer mode. EventList will fire the corresponding listening event when it adds the listener event emit via add for administrative messages
function Publisher(){ this.eventList={} } Publisher.prototype={ add:function(type, handle){ if(! this.eventList[type]){ this.eventList[type] = []; } this.eventList[type].push(handle) }, Emit: function () {const type = Array. The prototype. The shift. The call (the arguments) if (this. EventList [type]) { this.eventList[type].forEach((handle)=>{ handle.apply(this, arguments) }) } }, remove: function (type, handle) { let handles = this.eventList[type] if(handles){ if(! handle){ handles.length = 0 }else{ const index = handles.findIndex((_handle)=>handle! =_handle) if(index>=0){handles.splice(i,1)}; } } } } let p = new Pubsub(); p.add('num',(a)=>{console.log(a)} p.add('num',(a)=>{console.log(a+1)} p.emit('num',1) p.remove('num',(a)=>{console.log(a+1)) p.emit('num',1)Copy the code