工厂方法模式 与 类 和 构造函数 有什么区别?
首先要明确一个概念, JavaScript 中,任何函数都能返回一个新的对象。当这个函数不是构造函数或 class 时,它就叫做工厂函数。
为什么将 工厂方法模式 与 构造函数 单独区分开?其中 类 是 构造函数 的语法糖,暂不讨论。
// 构造函数模式
function Car(model, brand, price) {
this.model = model;
this.brand = brand;
this.price = price;
}
Car.prototype.move = function () {
console.log('di di di...');
}
const lingke = new Car('03', '领克', 16);
console.log(lingke);
const mrb = new Car('迈锐宝xl', '雪佛兰', 16);
console.log(mrb);
// 如果修改这个对象,则会影响所有
Car.prototype.move = function() {
console.log('driving...');
}
lingke.move() // driving...
// 工厂方法模式
function genCar(model, brand, price) {
// 这里主要是与构造函数形式区分开,大部分时候可以考虑通过 Object.create 创建
return {
model,
brand,
price,
move: function() {
console.log('di di di ...');
}
};
}
const lingke = genCar('03', '领克', 16);
console.log(lingke);
const mrb = genCar('迈锐宝xl', '雪佛兰', 16);
console.log(mrb);
1. 形式上
使用 构造函数 必须通过 new 的形式创建,而 工厂方法 就是普通函数的调用形式;
2. 本质上
-
构造函数主要是原型模式实现,它有一套特殊的结构原型链,所以它可以通过instanceof判断它的来源; -
构造函数是基于prototype对数据进行共享。 -
而
工厂方法模式每个对象相互独立,不会彼此影响。