JavaScript设计模式之工厂模式

工厂模式是用来创建对象的一种最常用的设计模式。
把创建对象的具体逻辑封装在一个函数中,那么这个函数就可以被视为一个工厂。
工厂模式根据抽象程度的不同可以分为:简单工厂,工厂方法和抽象工厂。

简单工厂模式

简单工厂模式又叫静态工厂模式,由一个工厂对象决定创建某一种产品对象类的实例。主要用来创建同一类对象的不同实例。

function createPerson (name,age) {
  var person = new Object();
  person.name = name;
  person.age = age;
  return person;
}

var Holz = createPerson ("Holz", "21");
console.log(Holz);  //{age:"21",name:"Holz"}  
var Tom = createPerson ("Tom", "7");
console.log(Tom);  // {age:"7",name:"Tom"}

抽象工厂模式

与简单工厂函数不同的是,抽象工厂函数会先设计好接口,具体的实现在子类中进行。

var abstractCreatePerson = function () {};

abstractCreatePerson.prototype = {
  selfIntroduction: function () {
    throw new Error("请先实例化此方法!");
  }
}

var student = Object.create(abstractCreatePerson.prototype);
student.selfIntroduction = function () {
  console.log("I am a sutdent, my name is holz!");
}
student.selfIntroduction();  //I am a sutdent, my name is holz!

var teacher = Object.create(abstractCreatePerson.prototype);
teacher.selfIntroduction = function () {
  console.log("I am a teacher, my name is xxxx!");
}
teacher.selfIntroduction();  //I am a teacher, my name is xxxx!

猜你喜欢

转载自blog.csdn.net/lixinyi0622/article/details/84641400
今日推荐