《JavaScript设计模式》笔记之第一、二章
第一章
创建一个类
第二章
方法三:鸭式辩型模仿接口
Interface 类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
Interface.ensureImplements = function (object) { if (arguments.length < 2) { throw new Error( "Interface.ensureImplements函数接收到的参数个数:" +arguments.length+ ",但是函数需要的参数个数为:2" ); } for ( var i = 1, len = arguments.length; i < len; i++) { var interface = arguments[i]; if (interface.constructor !== Interface) { throw new Error( "Interface.ensureImplements函数需要参数2以及后面的参数为Interface实例" ) } for ( var j = 0, methodsLen = interface.methods.length; j < methodsLen; j++) { var method = interface.methods[j]; if (!object[method] || typeof object[method] !== ‘function‘ ) { throw new Error( "Interface.ensureImplements函数: 实例没有实现以下方法:" +interface.name); } } } }; |
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
|
<html> <body> <script> //Interface 类 var Interface = function (name, methods) { if (arguments.length != 2) { throw new Error( "Interface constructor called with " + arguments.length + "arguments, but expected exactly 2." ); } this .name = name; this .methods = []; for ( var i = 0, len = methods.length; i < len; i++) { if ( typeof methods[i] !== ‘string‘ ) { throw new Error( "Interface constructor expects method names to be" + "passed in as a string." ); } this .methods.push(methods[i]); } }; Interface.ensureImplements = function (object) { if (arguments.length < 2) { throw new Error( "Interface.ensureImplements函数接收到的参数个数:" + arguments.length + ",但是函数需要的参数个数为:2" ); } for ( var i = 1, len = arguments.length; i < len; i++) { var interface = arguments[i]; if (interface.constructor !== Interface) { throw new Error( "Interface.ensureImplements函数需要参数2以及后面的参数为Interface实例" ) } for ( var j = 0, methodsLen = interface.methods.length; j < methodsLen; j++) { var method = interface.methods[j]; if (!object[method] || typeof object[method] !== ‘function‘ ) { throw new Error( "Interface.ensureImplements函数: 实例没有实现以下方法:" + interface.name); } } } }; //定义了一个接口,接口需要有run方法和jump方法 var Animal = new Interface( ‘Animal‘ ,[ ‘run‘ , ‘jump‘ ]); //实现Animal接口的Cat类 function Cat() {} Cat.prototype.run = function () {}; Cat.prototype.jump = function () {}; //实现Animal接口的Dog类 function Dog() {} Dog.prototype.run = function () {}; Dog.prototype.jump = function () {}; //没有实现Animal的Car类 function Car() {} Car.prototype.drive = function () {}; //有一只猫叫cat,有一只狗叫dog,有一部车叫car var cat = new Cat(); var dog = new Dog(); var car = new Car(); //假设一个人叫啊Mark,然后他很喜欢收养动物,今天他又来收养动物了。 var Mark = { adopt: function (animal) { Interface.ensureImplements(animal, Animal); console.log( "收养一只" +animal.constructor.name+ "成功" ); } }; Mark.adopt(cat); Mark.adopt(dog); Mark.adopt(car); </script> </body> </html> |
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。