javascript工厂模式、单例模式

//工厂模式
function createObject(name,age){
    var obj = new Object();
    obj.name = name;
    obj.age = age;
    obj.fun = function(){
        return this.name + this.age +"一个方法";
    }
    return obj;
}
var box1 = createObject("box1",1);
var box2 = createObject("box2",2);
alert(box1.fun());
alert(box2.fun());
//这里的box1和box2都是Object,无法无别类型与构造函数方式写一个类的区别在于没有使用this,而是每次都构造一个空对象,然后给其添加属性。创建对象方式不是使用new,而是使用函数调用方式。这种方式基本上用来替代一个类(具有相同属性的对象),而复杂一些的工厂则可以造不同类型的对象。
//构造函数
function Box(name,age){
 this.name = name;
 this.age = age;
 this.fun= function(){
  return this.name + this.age +"一个方法";
 }
}

function Red(name,age){
 this.name = name;
 this.age = age;
 this.fun= function(){
  return this.name + this.age +"一个方法";
 }
}
 var box1 = new Box("box1",1);
 var box2 = new Red("red",2);
//这里的box1和box不是一个对象,box1是Box对象,而box2是Red对象

优:主要好处就是可以消除对象间的耦合,通过使用工程方法而不是new关键字。将所有实例化的代码集中在一个位子防止代码重复。

缺:大多数类最好使用new关键字和构造函数,可以让代码更加简单易读。而不必去查看工厂方法来知道。
 
//单例模式
var mask;
var createMask = function(){
   if ( mask ) return mask;
   else{
      mask = document,body.appendChild(  document.createElement(div)  );
      return mask;
   }
}
//的确完成了一个产生单列对象的函数。这个函数是存在一定副作用的, 函数体内改变了外界变量mask的引用, 在多人协作的项目中, createMask是个不安全的函数. 另一方面, mask这个全局变量并不是非需不可. 再来改进一下.
var createMask = function(){
  var mask;
  return function(){
      return mask || ( mask = document.body.appendChild( document.createElement('div') ) )
  }
}()
//用了个简单的闭包把变量mask包起来, 至少对于createMask函数来讲, 它是封闭的.
原文地址:https://www.cnblogs.com/chenlogin/p/5121296.html