工厂方法模式 与 类 和 构造函数 的区别?

97 阅读1分钟

工厂方法模式构造函数 有什么区别?

首先要明确一个概念, 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. 本质上

  1. 构造函数 主要是 原型模式 实现,它有一套特殊的结构 原型链,所以它可以通过 instanceof 判断它的来源;

  2. 构造函数 是基于 prototype 对数据进行共享。

  3. 工厂方法模式 每个对象相互独立,不会彼此影响。