工厂模式 抽象工厂模式

昨天我们说到了简单工厂模式,今天我们来说说工厂模式,还有抽象工厂模式。

工厂模式,顾名思义,就是在简单工厂模式的基础上继续优化,前面的简单模式当数量多时要改的地方很多,而且比较分散,修改起来比较麻烦,那么我们可以继续封装下。

var BookShop=function(type,content){
  if(type in BookShop.types){
    return new BookShop.types[type](content);
  }else{
    alert("未找到对象"+type);
  }
}
BookShop.types={
  Book:function(content){
    this.name="Book";
    this.content=content;
  },
  Newspaper:function(content){
    this.name="Newspaper";
    this.content=content;
  },
  Magazine:function(content){
    this.name="Magazine";
    this.content=content;
  }
};
var book=BookShop("Book","书");
var news=BookShop("Newspaper","报纸");
var mag=BookShop("Magazine","杂志");
console.log(book)
console.log(news)
console.log(mag)

通过上面的分装以后我们添加其他类就比较容易了,以后如果有新添加的只需在types里面增加就行了。就比如组件开发,后期有组件就只要直接添加到里面就好了,其他地方就不需要改了。这样可以减少出错率,加快效率,当然也更好维护。

抽象函数就是用来继承的,它是一个规范,给这一类对象定义了一些功能,它规定了一些方法你如果用的话就必须重写。如果没重写你去使用的话就会报错。

var absFactory=function(sonClass,parentClass){
  if(typeof absFactory[parentClass] === "function"){
    var F = function(){};
    F.prototype = absFactory[parentClass].prototype;
    sonClass.prototype = new F();
    sonClass.prototype.constructor=sonClass;
  }else{
    alert("未找到该对象")
  }
}
absFactory.Book=function(){};
absFactory.Book.prototype={
  getPrice:function(){
    return new Error('用之前必须重写');
  },
  getName:function(){
    return new Error('用之前必须重写');
  }
}
absFactory.Newspaper=function(){};
absFactory.Newspaper.prototype={
  getType:function(){
    return new Error('用之前必须重写');
  },
  getLocal:function(){
    return new Error('用之前必须重写');
  }
}

absFactory.Magazine=function(){};
absFactory.Magazine.prototype={
  getPrice:function(){
    return new Error('用之前必须重写');
  },
  getType:function(){
    return new Error('用之前必须重写');
  }
}

上面三个就是在一个工厂里面的三个抽象函数,在函数的原型上我们定义了函数自身必须要用的功能。

console.log("--------书-------");
var Letter=function(name,price){
  this.name=name;
  this.price=price;
}
absFactory(Letter,'Book');
var letter=new Letter("明天","100");
console.log(letter);
console.log(letter.getName());
console.log(letter.getPrice());
Letter.prototype.getPrice=function(){
  return this.name;
}
Letter.prototype.getName=function(){
  return this.price;
}
console.log(letter.getName());
console.log(letter.getPrice());

console.log("--------杂志-------");
var Cartoon=function(price,type){
  this.price=price;
  this.type=type;
}
absFactory(Cartoon,'Newspaper');
Cartoon.prototype.getPrice=function(){
  return this.price;
}
Cartoon.prototype.getType=function(){
  return this.type;
}
var cartoon=new Cartoon(59,"写实风格");
console.log(cartoon.getType());
console.log(cartoon.getPrice());

简而言之,工厂模式是用来创建类产品的实例,抽象工厂模式是用来对这种类的一些功能的规定。

posted @ 2016-11-16 22:32  t_evening  阅读(206)  评论(0编辑  收藏  举报