前言
了解前端常见设计模式,使代码更加系统化与规范化
工厂模式
工厂方法模式是一种实现”工厂”概念的面向对象设计模式,它是最常用的实例化对象模式,是用工厂方法代替new操作的一种模式。
工厂模式要点
- 工厂接口是工厂方法模式的核心,与调用者直接交互用来提供产品。
- 工厂实现决定如何实例化产品,是实现扩展的途径,需要有多少种产品,就需要有多少个具体的工厂实现。
简单工厂模式
- 优点:可以解决创建多个相似对象的问题
- 缺点:未解决对象识别的问题
1 2 3 4 5 6 7 8 9 10 11 12 13
| function Factory(name,age,sex){ let person = {}; person.name = name; person.age = age; person.sex = sex; person.say = function(){ return this.name; }; return person; }
let tom = new Factory('Tom','10','male'); let jerry = new Factory('Jerry','20','female');
|
复杂工厂模式
复杂工厂模式与简单工厂模式对比,主要区别就是它不是另外使用一个对象或者类来创建实例,而是使用一个子类。工厂是一个将其成员对象的实例化推迟到子类中进行的类,子类可以重写父类接口方法以便创建时指定独自的对象类型 父类只对创建过程中的一般性问题进行处理,子类继承,但子类之间相互独立,具体业务再各自实现 父类变为抽象类,不能被实例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| function Factory(name){ this.name = name; this.say = function(){ return this.name; } } Factory.prototype = { constructor: Factory, createFactory: function(){ throw new Error('父类抽象类无法直接调用,需要子类重写'); } }
function extend(sub,sup){ let F= function(){}; F.prototype = sup.prototype; sub.prototype = new F(); sub.prototype.constructor = sub; sub.sup = sup.prototyp; if(sup.prototype.constructor === Object.prototype.constructor){ sup.prototype.constructor = sup; } }
function Person(name){ this.name = name; Factory.call(this,name); }
extend(Person,Factory);
Person.prototype.createFactory = function(){ switch(this.name){ case 'Tom': return {name: 'Tom', age: 10, sex: 'male'}; case 'Jerry': return {name: 'Jerry', age: 20, sex: 'female'}; default : return {}; } }
let Tom = new Person('Tom'); let tom1 = Tom.createFactory();
|
观察者模式
概念
它定义对象间一对多的依赖关系,当一个对象发生变化时,所有依赖于它的对象都将得到通知。
基本模式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| function EventTarget(){ this.handlers = {}; } EventTarget.prototype = { constructor: EventTarget, addHandler: function(type, handler){ if (typeof this.handlers[type] == "undefined"){ this.handlers[type] = []; } this.handlers[type].push(handler); }, fire: function(event){ if (!event.target){ event.target = this; } if (this.handlers[event.type] instanceof Array){ var handlers = this.handlers[event.type]; for (var i=0, len=handlers.length; i < len; i++){ handlers[i](event); } } }, removeHandler: function(type, handler){ if (this.handlers[type] instanceof Array){ var handlers = this.handlers[type]; for (var i=0, len=handlers.length; i < len; i++){ if (handlers[i] === handler){ break; } } handlers.splice(i, 1); } } };
|
观察者模式可以用于模块间通讯,订阅用户的事件、状态,触发执行相应的逻辑处理。
代理模式
定义
为其他对象提供一种代理以控制对这个对象的访问。在某些情况下,一个对象不适合或者不能直接引用另一个对象,而代理对象可以在客户端和目标对象之间起到中介的作用
优缺点
策略模式
定义
定义一系列的算法,把它们一个个封装起来,并且使它们可以相互替换。
- 优点
可以避免很多if语句,可以将需要的条件封装成类
通过类的形式声明对象,可以很方便的进行拓展