简介
工厂模式是设计模式中一种最常用的创建型设计模式。我们之所以称其为创建型模式是因为它主要用来创建新的对象。在实际开发过程中你常常会遇到需要创建对象的情况,这些对象可能大同小异,每次单独创建会增加代码量且不易于后期维护,所以就可以将这一部分封装为公共方法,命名为工厂方法。
举个例子: 老王是一家文具厂的厂长,文具厂里可以生产多种文具,当零售商到文具厂批发货物时会指定要购买哪种文具。
// 父类文具
class Stationery {
getType(){
console.log(this.type);
}
}
// 钢笔
class Pen extends Stationery {
constructor(){
super();
this.type = 'pen';
}
intruduce(){
console.log("Hi, I'm a " + this.type +" I can write.");
}
}
// 橡皮
class Eraser extends Stationery {
constructor(){
super();
this.type = 'eraser';
}
intruduce(){
console.log("Hi, I'm an " + this.type +" I can erase.");
}
}
// 笔记本
class NoteBook extends Stationery{
constructor(){
super();
this.type = 'notebook';
}
intruduce(){
console.log("Hi, I'm a " + this.type +" I can read.");
}
}
// 文具工厂
class StationeryFactory{
getStationery(type){
if(!type){
return null;
}
if(type.toLowerCase() == "pen"){
return new Pen();
}
if(type.toLowerCase() == "eraser"){
return new Eraser();
}
if(type.toLowerCase() == "notebook"){
return new NoteBook();
}
return null;
}
}
let stationeryFactory = new StationeryFactory();
let stationery1 = stationeryFactory.getStationery("notebook");
stationery1.intruduce();
let stationery2 = stationeryFactory.getStationery("eraser");
stationery2.intruduce();
如上面的代码,所有的文具都有个Stationery 父类可以从其继承一些公共属性和方法。StationeryFactory是文具工厂类,用于创建文具,通过传参获取具体的文具产品。
优缺点
可以看出来目前工厂里生产钢笔、橡皮、笔记本三种文具。老王如果想扩展生意需要多加入一些文具产品,这看上去也很容易实现,只需要多创建几个类就可以了。不过按照这种模式的话,每次增加一个产品时,都需要增加一个具体类,使得系统中类的个数成倍增加,在一定程度上增加了系统的复杂度。
总结
工厂模式相对来是一种很容易理解的设计模式,因为它使用的场景是创建某种或某类具体的对象。虽然在写法上不尽相同,但工厂模式本质上都是基于继承和多态的一种对象获取方式。