工厂模式就是创建一个对象,然后该对象可以批量产生需要的数据。一个工厂能提供一个创建对象的公共接口,我们可以在其中指定我们希望被创建的工厂对象的类型。
就像现实中实现了自动化生产的工厂,具有统一的流水线,比如生产一个袜子有袜子的设计和袜子的生成两大部分:袜子设计───原料颜色打样───定购原料───袜子打样───确定工艺;袜体生产-——下机检验————缝头拷口——定型整烫———整理包装;不一样的袜子制作,只需要改变原料、颜色和样式就可以制作出来不一样的产品。
工厂模式有三种模式,简单工厂模式、复杂工厂模式、抽象工厂模式。我们这一章主要探究简单工厂模式和复杂工厂模式。
一、简单工厂模式
简单工厂模式又叫静态工厂模式,由一个工厂对象决定创建某一种产品对象类的实例。主要用来创建同一类对象。因为简单工厂模式比较简单,传递的参数比较少,而且不需要知道函数内部的方法具体的逻辑。
比如说上边的例子,一个工厂需要生产一些袜子和裤子以及鞋子,那么只需要构建一个简单的工厂模式,如下:
let UserFactory = function (product) {
function Clothes() {
this.name = "衣服"
this.colors= ['red', 'white', 'black', 'blue']
this.styles=['diy', 'circular']
this.consoleSay=function(){
console.log("我是衣服")
}
}
function Trousers() {
this.name = '裤子'
this.colors= ['red', 'white', 'black', 'blue']
this.styles=['diy', 'circular']
this.consoleSay=function(){
console.log("我是裤子")
}
}
function Shoes() {
this.name = "鞋子"
this.colors= ['red', 'white', 'black', 'blue']
this.styles=['diy', 'circular',‘flat’]
this.consoleSay=function(){
console.log("我是鞋子")
}
}
switch (product) {
case 'Clothes':
return new Clothes();
break;
case 'Trousers':
return new Trousers();
break;
case 'Shoes':
return new Shoes();
break;
default:
throw new Error('参数错误, 可选参数:superAdmin、admin、user');
}
}
//调用
let Clothes= UserFactory('Clothes');
let Trousers= UserFactory('Trousers')
let Shoes= UserFactory('Shoes')
只需要传入生产的物品名称,那么就可以生产出一批相对应的产品。但是,这种方式很容易造成修改错误,因为当我们需要添加一个“包包”的时候,就得改两处代码。这个时候,我们可以考虑使用复杂工厂模式。
二、复杂工厂模式
工厂方法模式跟简单工厂模式差不多,但是把具体的产品放到了工厂函数的prototype中。这样一来,扩展产品种类就不必修改工厂函数了,也可以随时重写某种具体的产品。
function factory(type){
if(this instanceof factory){
return new this[type]();
}else{
return new factory(type);
}
}
factory.prototype = {
'Clothes': function() {
this.name = "衣服",
this.colors= ['red', 'white', 'black', 'blue']
this.styles=['diy', 'circular']
this.consoleSay=function(){
console.log("我是衣服")
}
}
'Trousers': function() {
this.name = "裤子",
this.colors= ['red', 'white', 'black', 'blue']
this.styles=['diy', 'circular']
this.consoleSay=function(){
console.log("我是裤子")
}
}
'Clothes': function() {
this.name = "鞋子",
this.colors= ['red', 'white', 'black', 'blue']
this.styles=['diy', 'circular']
this.consoleSay=function(){
console.log("我是鞋子")
}
}
}
var Clothes= factory('Clothes')
如果我要添加包包,只需要在factory的prototype中进行添加就可以,如下:
...
'Bags': function() {
this.name = "包包",
this.colors= ['red', 'white', 'black', 'blue']
this.styles=['diy', 'circular']
this.consoleSay=function(){
console.log("我是包包")
}
...