-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbstractFactoryModule.js
More file actions
56 lines (50 loc) · 1.36 KB
/
AbstractFactoryModule.js
File metadata and controls
56 lines (50 loc) · 1.36 KB
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
//Type.js 构造函数存放文件
//定义car构造函数
function Car(options){
//默认值
this.doors = options.doors || 4;
this.state = options.state || "brand new";
this.color = options.color || "silver";
}
//定义trunk构造函数
function Truck(options){
this.state = options.state || "used";
this.wheelSize = options.wheelSize || "large";
this.color = options.color || "blue";
}
var AbstractVehicleFactory = (function(){
//存储车辆类型
var types = {};
return {
getVehicle :function(type,customizations){
var Vehicle = types[type];
return (Vehicle) ? new Vehicle(customizations) : null;
},
registerVehicle:function(type,Vehicle){
var proto = Vehicle.prototype;
//只注册实现车辆契约的类
if(!proto.drive&&!proto.breakDown){
types[type] = Vehicle;
}
return AbstractVehicleFactory;
},
types:types,
}
})();
//用法
AbstractVehicleFactory.registerVehicle("car",Car);
AbstractVehicleFactory.registerVehicle("truck",Truck);
//基于抽象车辆类型实例化一个新car对象
var car = AbstractVehicleFactory.getVehicle("car",{
color:"lime green",
state:"like new"
})
//同理实例化一个新truck对象
var truck = AbstractVehicleFactory.getVehicle("truck",{
wheelSize:"medium",
color:"neon yellow"
})
//输出car以及truck对象
console.log(AbstractVehicleFactory.types);
console.log(car);
console.log(truck);