-
Notifications
You must be signed in to change notification settings - Fork 0
/
3_工厂模式.js
78 lines (75 loc) · 1.42 KB
/
3_工厂模式.js
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
/**
* 简单工厂模式:创建一个新对象,然后包装增强其属性和功能实现
* 与类实例化创建不同:类实例化的对象可以共享方法,而简单工厂模式创建的每个对象都是新的
*/
function createObj(type, text) {
var o = new Object();
o.content = text;
switch (type) {
case 1:
o.get = function() {}
break;
case 2:
o.set = function() {}
break;
default:
// statements_def
break;
}
return o;
}
/**
* 安全模式类: 防止调用者 遗漏new关键字
*/
var Demo = function() {
if (!this instanceof Demo) {
return new Demo();
}
}
Demo.prototype.show = function() {};
/**
* 安全工厂方法
*/
var Factory = function(type, content) {
if (this instanceof Factory) {
return new this[type](content);
} else {
return new Factory(type, content);
}
}
Factory.prototype = {
java: function() {},
UI: function() {},
JavaScript: function(content) {
this.content = content;
(function(content) {
console.log('javascript :' + content);
})(content)
}
}
//调用
var data = [{
type: 'java',
content: ''
}, {
type: 'UI',
content: ''
}, {
type: 'JavaScript',
content: 'GO!'
}];
data.forEach(function(v, i, a) {
Factory(v.type, v.content);
})
/**
* 抽象工厂模式 Abstract Factory
*/
//抽象类
var Car = function () {}
Car.prototype={
getPrice:function(){
throw new Error('抽象方法不能调用')
}
}
var c = new Car();
c.getPrice();