-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2、工厂模式.js
87 lines (71 loc) · 1.89 KB
/
2、工厂模式.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
78
79
80
81
82
83
84
/**
* 安全的工厂模式
*/
(function () {
var Factory = function (type, content) {
if (this instanceof Factory) {
return new this[type](content)
} else {
return new Factory(type, content)
}
}
Factory.prototype = {
JS: function (content) {
this.content = content;
this.addMethod = function () {
}
console.log(content);
},
JAVA: function (content) {
console.log(content);
},
PHP: function (content) {
console.log(content);
}
}
var F = new Factory('JS', 'This is Javascript');
console.log(F)
Factory('PHP', 'This is PHP');
}());
/**
* 抽象工厂模式(Abstract Factory)
*/
(function(){
//抽象工厂方法
var VehicleFactory = function(subType,superType) {
if(typeof VehicleFactory[superType] === 'function'){
function F() {}
F.prototype = new VehicleFactory[superType]();
subType.constructor = subType;
// console.dir(subType.constructor);
subType.prototype = new F();
}else{
throw new Error('未创建该抽象类');
}
}
VehicleFactory.Car = function () {
this.type = "Car"
}
VehicleFactory.Car.prototype = {
getPrice : function() {
return new Error('抽象方法不能调用');
},
getSpeed: function () {
return new Error('抽象方法不能调用');
}
}
var BMW = function(price,speed) {
this.price = price;
this.speed = speed;
}
VehicleFactory(BMW,'Car');
BMW.prototype.getPrice = function(){
return this.price;
}
BMW.prototype.getSpeed = function () {
return this.speed;
}
var B = new BMW(1000,999);
console.log(B.getPrice())
console.log(B.type)
}())