javascript设计模式(一)

1.工厂模式:工厂模式类似与java中的class,一次定义可以多次产生相同的对象。
function Person(params){
  var person = new Object();
  person.name = params.name;
  person.sex = params.sex;

  person.hit = function(){
    consolse.log("hit him);
  };
}

2.单体模式:单体模式的两个标志:1.所有的成员变量都可以通过一个变量访问2.仅可以被实例化一次。
举个例子:

var Person = function(name){
  this.name = name;
  this.instance = null;
}
Person.prototype.getName = function(){
  return this.name;
};
function getInstance(name){
  if(!this.instance){
    this.instance = new Person(name);
  }
  return this.instance;
}

从上面的例子中我们可以看出Person这个类的实例对象通过getInstance方法获得,在其中对Person的实例个数进行了控制,并赋值给全局变量this.instance,这种情况下Person的实例对象就永远只存在一个。

posted @ 2017-10-10 17:51  灵魂创造者  阅读(112)  评论(0)    收藏  举报