Repository navigation
Expand file tree
/
Copy path1 - Structure of the decorator.js
More file actions
92 lines (82 loc) · 2.6 KB
/
Copy path1 - Structure of the decorator.js
File metadata and controls
92 lines (82 loc) · 2.6 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
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
/* The Bicycle interface. */
// 自行车接口
var Bicycle = new Interface('Bicycle', ['assemble', 'wash', 'ride', 'repair',
'getPrice']);
/* The AcmeComfortCruiser class. */
// 创建一辆自行车
var AcmeComfortCruiser = function() { // implements Bicycle
//todo
};
AcmeComfortCruiser.prototype = {
assemble: function() {
//todo
},
wash: function() {
//todo
},
ride: function() {
//todo
},
repair: function() {
//todo
},
getPrice: function() {
return 399.00;
}
};
/* The BicycleDecorator abstract decorator class. */
// 创建装饰者的抽象类,继承者Bicycle接口
var BicycleDecorator = function(bicycle) { // implements Bicycle
Interface.ensureImplements(bicycle, Bicycle);
this.bicycle = bicycle;
}
BicycleDecorator.prototype = {
assemble: function() {
return this.bicycle.assemble();
},
wash: function() {
return this.bicycle.wash();
},
ride: function() {
return this.bicycle.ride();
},
repair: function() {
return this.bicycle.repair();
},
getPrice: function() {
return this.bicycle.getPrice();
}
};
/* HeadlightDecorator class. */
// 创建一个装饰者
var HeadlightDecorator = function(bicycle) { // implements Bicycle
this.superclass.constructor(bicycle); // Call the superclass's constructor.
}
extend(HeadlightDecorator, BicycleDecorator); // Extend the superclass.
HeadlightDecorator.prototype.assemble = function() {
return this.bicycle.assemble() + ' Attach headlight to handlebars.';
};
HeadlightDecorator.prototype.getPrice = function() {
return this.bicycle.getPrice() + 15.00;
};
/* TaillightDecorator class. */
// 创建一个装饰者
var TaillightDecorator = function(bicycle) { // implements Bicycle
this.superclass.constructor(bicycle); // Call the superclass's constructor.
}
extend(TaillightDecorator, BicycleDecorator); // Extend the superclass.
TaillightDecorator.prototype.assemble = function() {
return this.bicycle.assemble() + ' Attach taillight to the seat post.';
};
TaillightDecorator.prototype.getPrice = function() {
return this.bicycle.getPrice() + 9.00;
};
/* Usage. */
var myBicycle = new AcmeComfortCruiser(); // Instantiate the bicycle.
alert(myBicycle.getPrice()); // Returns 399.00
myBicycle = new TaillightDecorator(myBicycle); // Decorate the bicycle object
// with a taillight.
alert(myBicycle.getPrice()); // Now returns 408.00
myBicycle = new HeadlightDecorator(myBicycle); // Decorate the bicycle object
// again, now with a headlight.
alert(myBicycle.getPrice()); // Now returns 423.00