单例模式
let obj = { ?name: ‘xx‘, ?age: 20}
工厂模式
function Person() { this.name = ‘Person1‘; }function Animal() { this.name = ‘Animal1‘; }function Factory() {}Factory.prototype.getInstance = function(className) { ?return eval(‘new ‘ + className + ‘()‘);}var factory = new Factory();var obj1 = factory.getInstance(‘Person‘);var obj2 = factory.getInstance(‘Animal‘);console.log(obj1.name); // Person1console.log(obj2.name); // Animal1
代理模式
function Person() { }Person.prototype.sayName = function() { console.log(‘michaelqin‘); }Person.prototype.sayAge = function() { console.log(30); }function PersonProxy() { ??this.person = new Person(); ?const that = this; ?this.callMethod = function(functionName) { ???console.log(‘before proxy:‘, functionName); ???that.person[functionName](); // 代理 ???console.log(‘after proxy:‘, functionName); ?}}var pp = new PersonProxy();pp.callMethod(‘sayName‘); // 代理调用Person的方法sayName()pp.callMethod(‘sayAge‘); // 代理调用Person的方法sayAge() ???
观察订阅者模式
function Publisher() { ?this.listeners = [];}Publisher.prototype = { ?addListener(listener){ ???this.listeners.push(listener); ?}, ?removeListener(listener){ ???delete this.listeners[listener]; ?}, ?notify(obj){ ???this.listeners.forEach(listener => { ?????if(typeof listener !== ‘undefined‘){ ???????listener.process(obj); ?????} ???}) ?}}function Subscriber() { ?}Subscriber.prototype = { ?process(obj){ ???console.log(obj) ?}}const p = new Publisher();
js设计模式
原文地址:https://www.cnblogs.com/colima/p/8687123.html