6、javascript --工厂方法模式

对于使用 instanceof 属性不太了解的看,参考这个:

http://www.cnblogs.com/Uncle-Keith/p/5834289.html

 

instanceof运算符

  instanceof运算符返回一个布尔值,表示指定对象是否为某个构造函数的实例。

1     function A() {};
2     var a = new A();
3     console.log(a instanceof A);    //true

  因为instanceof对整个原型链上的对象都有效,所以同一个实例对象,可能会对多个构造函数都返回true。

1     function A() {};
2     var a = new A();
3     console.log(a instanceof A);    //true
4     console.log(a instanceof Object);    //true

 

 

5.1、简单工厂方法

工厂方法模式:通过对产品类的抽象使其创建业务主要负责用于创建多个类产品的实例。

 

先看下边例子:

 1 //创建两个类
 2 var class1 = function(content){
 3     this.content = content;
 4     saygood : function(){
 5         console.log(this.content);
 6     }
 7 }
 8 
 9 var class2 = function(content){
10     this.content = content;
11     saygood function(){
12         console.log(this.console);
13     }
14 }
15 
16 
17 //创建工厂
18 function factory(type,content){
19     switch(type){
20         case'class1':
21           return new class1(content);
22           break;
23         case 'class2':
24           return new class2(content);  
25     }
26 }
27 
28 //调用
29 factory('class1','helloclass1');

这种方式对于需求简单可以使用,需求是变化的,增加一个类意味着 工厂也随之改变,这样并不能满足需求。在下边会介绍:

5.2、安全模式

什么叫安全模式?

安全模式类是说可以屏蔽使用这个类的错误造成的错误。比如我们创建一个类,在掉用时候并没有实例化,着样就会报错为了避免这个问题发生  

 1 var safe = function(){
 2     //创建类
 3 }
 4 
 5 safe.prototype = {
 6     show : function(){
 7         console.log("good");
 8     }
 9 }
10 
11 var _safe = new safe();
12 _safe.show();  //good;
13 
14 var _safe1 = safe();
15 _safe1.show(); //.... show of undefined

这时你会发现报错是缺少 实例化 “new”  ,未实例化this 指向window ,未了避免这样发生可以这样创建对象。

 1 var safe = function(){
 2     if(!this instanceof safe){
 3         return new safe();
 4     }
 5 };
 6 safe.prototype = {
 7     show : function(){
 8         console.log("hello world");
 9     }
10 }
11 
12 var _safe = safe();
13 _safe.show(); // hello world

就算是被遗漏也不会出现错误。

 

5.3、安全的工厂方式
 1 //安全创建工厂类
 2 var factory = function(){
 3     if(!this instanceof factory){
 4         return new factory(type, content);
 5     }
 6 }
 7 
 8 factory.prototype = {
 9     init : function(type,obj){
10         if(!type)return;
11         this[type](obj);
12     },
13     show : function(obj){
14         console.log(obj.name);
15         console.log(obj.age);
16     }
17 
18 }
19 
20 var _factory = new factory();
21 var obj = {
22     name : 'cxd',
23     age : 26
24 }
25 _factory.init("show",obj);

 

这种方式 是通过安全工厂先做下判断instanceof 是否是实例,在调用传入obj对象,传入的参数会有很多个,封装到一个对象中。

  

 

posted on 2016-09-03 13:33  Mc525  阅读(151)  评论(0)    收藏  举报

导航