JavaScript设计模式(工厂模式)

简单工厂模式

创建型模式,又叫做静态工厂方法模式,不属于23种GOF设计模式。简单工厂模式是由一个工厂对象决定创建出哪一种产品类的实例。实例拥有共同的父类。

1
2
3
4
5
6
7
8
9
10
11
12
function Person(name, age, sex) {
var obj = {};
obj.name = name;
obj.age = age;
obj.sex = sex;
obj.sayHello = function() {
console.log('My name is' + this.name);
}
}
var person1 = new Person('Peter', 23, 'male');
var person2 = new Person('Helen', 22, 'female');

工厂方法模式

定义创建各类对象的接口,但是让子类决定实例化哪个类。工厂方法将类的实例化延迟到子类。
本质上就是根据不同的输入,创建出不同类型对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function Computer(type) {
let computer;
if (type === 'Macbook') {
computer = new Mackbook();
} else if (type === 'Surface') {
computer = new Surface();
}
}
function Macbook() {
this.price = 10000;
this.os = 'OSX';
}
function Surface() {
this.price = 9999;
this.os = 'windows';
}
var computer1 = Computer('Macbook');
var computer2 = Computer('Surface');
坚持原创技术分享,您的支持将鼓励我继续创作!