工厂模式与备忘录模式实例详解

工厂模式

适用于大批量创建同类型的对象,通过同一个接口创建对象,根据传入的参数不同从而创建不同内容的对象,让这个接口由子类决定实例化哪一个类。
优点:解决了多个类似对象声明的问题,易于维护和扩展,稳定性好。
推荐场景:1. 对象的构建十分复杂。 2. 需要依赖具体环境创建不同实例。 3. 处理大量具有相同属性的小对象。

实施过程:

  1. 提供父构造函数
  2. 设置父构造函数的原型对象
  3. 定制不同对象上的差异化属性(设置子构造函数–>父构造函数的静态方法)
  4. 在父构造函数上添加静态工厂方法
    1. 判断是否支持生产
    2. 设置子构造函数(父构造函数的静态方法)的原型对象
    3. 修正构造器属性
    4. 返回利用子构造函数创建的实例对象
  5. 使用父构造函数的静态工厂方法创建指定的对象

工厂模式示例图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//1. 提供父构造函数
function CarFactory() {}
//2. 设置父构造函数原型对象(共同属性)
CarFactory.prototype = {
rank: this.num,
bandName: function () {
console.log(this.carBand)
},
country: function () {
console.log(this.country)
}
};
//3. 定制不同对象差异化属性
CarFactory.benz = function () {
this.carBand = 'benz';
this.country = 'Germany';
this.num = 1;
};
CarFactory.audi = function () {
this.carBand = 'audi';
this.country = 'Germany';
this.num = 2;
};
CarFactory.bmw = function () {
this.carBand = 'bmw';
this.country = 'Germany';
this.num = 3;
};
//4. 在父构造函数上添加静态工厂方法
CarFactory.product = function (band) {
//容错处理,判断能否生产
if (typeof CarFactory[band] !== 'function') {
throw '目前不支持生产'; //抛出异常
}
//设置子构造函数的原型属性为父构造函数的实例,完成原型链继承
CarFactory[band].prototype = new CarFactory();
//修正构造器属性
CarFactory[band].prototype.constructor = CarFactory[band];
//让父构造函数的静态工厂方法返回子构造函数的的实例对象
return new CarFactory[band]();
};
//5. 利用父构造函数的静态方法创建对象
var benz = CarFactory.product('benz');
console.log(benz); //{carBand: "benz", country: "Germany", num: 1}
var audi = CarFactory.product('audi');
console.log(audi); //{carBand: "audi", country: "Germany", num: 2}
var volkswagen = CarFactory.product('volkswagen');
console.log(volkswagen); //不支持生产,抛出异常

备忘模式(函数结果缓存)

特定场景:当某个函数需要接受参数,可能会反复计算并且在函数内部需要进行耗时并且大量的逻辑处理才能得到结果时。我们可以把计算结果保存包函数对象中。计算时,先去缓存中查找,没有再计算。

函数是对象,可以在函数上面添加属性和方法

函数的参数作为key,结果作为value

步骤:

1. 提供一个缓存对象`cache`(key-value)
2. 获取传入的参数
3. 在缓存对象`cache`中查找是否有结果
4. 有,就返回
5. 没有,执行函数得到结果保存到`cache`中并返回结果。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var memento = function (param) {
//初次运行建立缓存
if (typeof memento.cache === 'undefined') {
memento.cache = {};
}
//如果有缓存就返回存储的结果
if (memento.cache[param] !== undefined) {
return memento.cache[param];
}
//没有就进行计算得到结果存储
var result = ''; //初始化计算结果
//复杂计算,结果保存到result
memento.cache[param] = result; //存储结果
return result;
};