-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfactory.html
422 lines (358 loc) · 13.6 KB
/
factory.html
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>工厂模式</title>
</head>
<body>
请打开控制台查看实例运行结果!!!
<script src="utils.js"></script>
<script>
window.onload = function () {
// 概述:工厂模式就是利用工厂函数创建并返回合适的实例(对象),将创建对象的逻辑解耦。
// ##### 简单工厂模式:用一个单体或者类生成并返回实例。 #####
/*
自行车商店实例:
一个商店有多种类型的自行车出售。
*/
console.log('自行车商店实例:');
// 自行车
function Speedster() {};
Speedster.prototype = {
assemble () {
console.log('assemble');
},
wash () {
console.log('wash');
},
ride () {
console.log('ride');
},
repair () {
console.log('repair');
}
}
// 定义一个Bicycle接口
let Bicycle = new Interface('Bicycle', ['assemble', 'wash', 'ride', 'repair']);
let BicycleShop = function() {};
BicycleShop.prototype = {
sellBicycle(model) {
let bicycle;
switch(model) {
case 'speedster':
bicycle = new Speedster();
break;
case 'lowrider':
bicycle = new Lowrider();
break;
case 'Comfort Cruiser':
default:
bicycle = new ComfortCruiser();
}
Interface.ensureImplements(bicycle, Bicycle);
bicycle.assemble();
bicycle.wash();
return bicycle;
}
};
let shop = new BicycleShop();
let newBike = shop.sellBicycle('speedster');
/*
以上例子的缺点是:如果新增一种车型,就要往switch中增加一个case,如果车型很多这部分代码会很臃肿,这部分代码可以通过工厂模式优化
/*
/*
使用「简单工厂模式」优化:
更好的做法是把创建新自行车的工作转交给简单工厂函数,让这个工厂函数返回合适的车型实例,这样优化后,只要有新车型,我们只需修改createBicycle方法,sellBicycle方法的逻辑也更加清晰
这里使用单体,当然也可以写成一个类
*/
let BicycleFactory = {
createBicycle(model) {
let bicycle;
switch (model) {
case 'speedster':
bicycle = new Speedster();
break;
case 'lowrider':
bicycle = new Lowrider();
break;
case 'Comfort Cruiser':
default:
bicycle = new ComfortCruiser();
}
Interface.ensureImplements(bicycle, Bicycle);
return bicycle;
}
};
BicycleShop.prototype = {
sellBicycle(model) {
let bicycle = BicycleFactory.createBicycle(model);
bicycle.assemble();
bicycle.wash();
return bicycle;
}
};
// 使用「工厂模式」优化:将工厂函数写成自身的抽象方法, 而不是像简单工厂函数那样把工厂函数写到另一个对象
// 好处是每个实例都能有不同的工厂函数,比如下面的例子,xds可以创建自己的工厂函数,另一个品牌,也可以创建自己的工厂函数。 #####
let BicycleShop2 = function () {};
BicycleShop2.prototype = {
sellBicycle(model) {
let bicycle = this.createBicycle(model);
bicycle.assemble();
bicycle.wash();
return bicycle;
},
// 抽象方法
createBicycle() {
throw new Error('不允许操作抽象类!')
}
}
// 喜德盛牌自行车子类!
let Xds = function() {};
extend(Xds, BicycleShop2); // 喜德盛继承自行车商城
Xds.prototype.createBicycle = function (model) {
let bicycle;
switch (model) {
case 'speedster':
bicycle = new Speedster();
break;
case 'lowrider':
bicycle = new Lowrider();
break;
case 'Comfort Cruiser':
default:
bicycle = new ComfortCruiser();
}
Interface.ensureImplements(bicycle, Bicycle);
return bicycle;
};
let xds = new Xds();
xds.sellBicycle('speedster');
/*
##### 工厂模式适用场景:#####
1 需要动态创建实现同一接口的对象时,(如上例,动态创建各种实现了Bicycle接口的自行车)这种类型的选择可以是显式或隐式的(上例自行车为显式,下例XHR为隐式)。
2 需要为对象进行复杂的设置时,这种设置当然可以分散地写在各种类中,但是最好用工厂模式将这种设置集中管理。
3 需要用各种小对象组成大对象时,像自行车的例子,可以把车轮、链条、车架等作为小对象,组成大对象自行车,某天需要新增或更换零件,工程模式使得这很容易做到。(下面RSS实例中演示了这种场景)
*/
// ##### 实例:XHR工厂 #####
let SimpleHandler = function() {};
SimpleHandler.prototype = {
request(method, url, callback, postVars = null) {
let xhr = this.createXhrObject();
xhr.onreadystatechange = function() {
if (xhr.readyState !== 4) return;
(xhr.status === 200) ?
callback.success(xhr.responseText, xhr.responseXML) :
callback.failure(xhr.status);
}
xhr.open(method, url, true);
xhr.send(postVars);
},
/*
工厂函数:创建并返回合适的xhr实例
这里使用了《高性能JavaScript》中说到的避免多次做同一件事的思想,参考我的总结:https://github.com/OuZuYu/fe-style-guide
*/
createXhrObject() {
let methods = [
function () { return new XMLHttpRequest(); },
function () { return new ActiveXObject('Msxml2.XMLHTTP') },
function () { return new ActiveXObject('Microsoft.XMLHTTP') }
];
for (let i of methods) {
try {
i();
} catch {
continue;
}
// memoizing技术
this.createXhrObject = i;
return i;
}
throw new Error('SimpleHandler:xhr对象创建失败,没有合适的xhr对象!');
}
}
/*
上面的例子用一个工厂函数动态创建xhr对象
假设还有两种封装xhr的类,那么还可以创建一个工厂函数创建合适的实例。
现在加上两种类,第一种是确保前面的请求已经成功,再请求;第二种是断网时,会先保存请求。
*/
let QueueHandler = function () {
this.queue = [];
this.requestInProgress = false; // 所有请求是否已完成标识
this.retryDelay = 5;
};
extend(QueueHandler, SimpleHandler);
// 如果还有请求未完成且不覆盖则先存到队列。
// 请求成功后,取队列中下一个继续请求。
QueueHandler.prototype.request = function (method, url, callback, postVars, override) {
if (this.requestInProgress && !override) {
this.queue.push({ method, url, callback, postVars, override });
} else {
this.requestInProgress = true;
let xhr = this.createXhrObject();
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) return;
if (xhr.status === 200) {
callback.success(xhr.responseText, xhr.responseXML);
this.advanceQueue();
} else {
callback.failure(xhr.status);
setTimeout(() => {
this.request(method, url, callback, postVars, override);
}, this.retryDelay * 1000);
}
}
xhr.open(method, url, true);
xhr.send(postVars);
}
}
QueueHandler.prototype.advanceQueue = function () {
if (this.queue.length === 0) {
this.requestInProgress = false;
return;
}
let req = this.queue.shift();
this.request(req.method, req.url, req.callback, req.postVars, true)
}
let OfflineHandler = function () {
this.storedRequests = [];
}
extend(OfflineHandler, SimpleHandler);
OfflineHandler.prototype.request = function (method, url, callback, postVars) {
if (XhrManager.isOffline()) {
this.storedRequests.push({
method,
url,
callback,
postVars
});
} else {
this.flushStoredRequests();
OfflineHandler.superclass.request(method, url, callback, postVars);
}
}
OfflineHandler.prototype.flushStoredRequests = function () {
for (let i of this.storedRequests) {
OfflineHandler.superclass.request(i.method, i.url, i.callback, i.postVars);
}
}
// 现在有三个封装xhr的类,那么可以用一个工厂函数创建合适的类。
let XhrManager = {
createXhrHandler() {
let xhr;
if (this.isOffline()) {
xhr = new OfflineHandler();
} else if (this.isHighLatency()) {
xhr = new QueueHandler();
} else {
xhr = new SimpleHandler();
}
Interface.ensureImplements(xhr, Ajaxhandler);
return xhr;
},
isOffline() {
// 用simpleHandler发起一个请求,如果成功则是有网
},
isHighLatency() {
// 用simpleHandler发起一系列请求,计算响应时间,看网络是否延迟严重。
}
}
// 现在可以使用这个工厂函数。
let myHandler = XhrManager.createXhrHandler();
myHandler.request('GET', 'script.php', {
success() {
},
failure() {
}
});
/* ##### RSS阅读器 #####
将一个xhr对象,一个显示列表的对象,一个配置对象组成RSS阅读器,这时适合用一个工厂函数返回这个RSS阅读器实例。
*/
// 定义一个显示列表的类。
let DisplayModule = new Interface('DisplayModule', ['append', 'remove', 'clear']);
let listDisplay = function (id, parent) {
this.list = document.createElement('ul');
this.list.id= id;
this.parent.append(this.list);
};
listDisplay.prototype = {
append(text) {
let newEl = document.createElement('li');
newEl.innerHTML = text;
this.list.append(newEl);
return newEl;
},
remove(el) {
this.list.removeChild(el);
},
clear() {
this.list.innerHTML = '';
}
}
// 配置对象
let conf = {
id: 'cnnRss',
feedUrl: '', // 获取rss数据的url
updateInterval: 60,
parent: document.getElementById('rssListWrap');
}
// 现在定义一个RSS阅读器类,参数为xhr类和listDisplay类以及conf配置对象。
let FeedReader = function (display, xhrHandler, conf) {
this.display = display;
this.xhrHandler = xhrHandler;
this.conf = conf;
this.startUpdate();
}
FeedReader.prototype = {
startUpdate() {
this.fetchFeed(); // 获取RSS数据
// 每隔一段时间获取一次
this.interval = setInterval(() => {
this.fetchFeed();
}, this.conf.updateInterval * 1000);
},
stopUpdate() {
clearInterval(this.interval);
},
fetchFeed() {
this.xhrHandler.request('GET', this.conf.feedUrl, {
success(text, xml) {
this.parseFeed(text, xml);
},
error(status) {
this.showError(status);
}
})
},
parseFeed(resText, resXml) {
this.display.append(`<a href='${resText}'>RSS</a>`);
},
showError() {
this.display.clear();
this.display.append('ERROR');
}
}
// 定义一个工厂函数把listDisplay实例、xhr实例、conf配置对象,这三个小对象组装成RSS对象。
let FeedManager = {
createFeedReader(conf) {
let displayModule = new listDisplay(conf.id, conf.parent);
Interface.ensureImplements(displayModule, DisplayModule);
let xhrHandler = XhrManager.createXhrHandler();
Interface.ensureImplements(xhrHandler, Ajaxhandler);
return new FeedReader(displayModule, xhrHandler, conf);
}
}
/* ##### 工厂模式利弊 #####
利:
1 消除对象间耦合
2 把实例化代码集中在一个位置
3 派生子类时更灵活(可以定义抽象类,推迟到子类中实例化)
弊:
1 比起new一个构造函数可读性相对较差,因为使用new一下子就能知道这是在实例化。
所以切勿滥用(详情ctrf + f 搜 "工厂模式适用场景")
*/
};
</script>
</body>
</html>