Skip to content

Commit fbb36a4

Browse files
committed
面向接口编程
1 parent 57cfd79 commit fbb36a4

File tree

1 file changed

+113
-0
lines changed

1 file changed

+113
-0
lines changed

twenty-chapter/index.js

+113
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
//接口和面向接口编程
2+
//接口 库和模块提供的api
3+
//java 等语言提供的关键字 interface
4+
//面向接口编程中的接口
5+
//接口是对象能响应的请求的集合
6+
7+
//抽象类和interface的作用主要是
8+
//1 通过向上转型来隐藏对象的真正类型,表现对象的多态性
9+
//2 约定类和类之间的一些契约行为
10+
// 动态类型语言中,对象的多态性是 与生俱来的
11+
12+
function show(obj){
13+
obj.show(); // Uncaught TypeError: undefined is not a function
14+
}
15+
16+
var myObject = {};
17+
show(myObject);
18+
19+
function show(obj){
20+
obj.show();
21+
}
22+
23+
var myObject = {
24+
show:1,
25+
}
26+
27+
show(myObject);
28+
29+
//此时,我们不得加上一些代码检查
30+
function show(obj){
31+
if(obj && typeof obj.show === 'function'){
32+
obj.show()
33+
}
34+
}
35+
36+
function show(obj){
37+
try{
38+
obj.show();
39+
}catch(e){
40+
console.log(e);
41+
}
42+
}
43+
44+
var myObject = {};
45+
show(myObject);
46+
47+
//用鸭子类型进行接口检查
48+
var isArray = function(obj){
49+
return obj && typeof obj === 'object' && typeof obj.length === 'number'
50+
&& typeof obj.splice === 'function';
51+
}
52+
53+
//用typescript 编写基于 interface 的命令模式
54+
var RefreshMenuBarCommand = function(){};
55+
RefreshMenuBarCommand.prototype.execute = function(){
56+
console.log("refresh menubar page");
57+
};
58+
59+
var AddSubMenuCommand = function(){};
60+
AddSubMenuCommand.prototype.execute = function(){
61+
console.log('add subMenu ');
62+
}
63+
64+
var DelSubMenuCommand = function(){};
65+
66+
var refreshMenuBarCommand = new RefreshMenuBarCommand();
67+
var addSubMenuCommand = new AddSubMenuCommand();
68+
var delSubMenuCommand = new DelSubMenuCommand();
69+
70+
var setCommand = function(command){
71+
document.getElementById('exeCommand').onclick = function(){
72+
if(typeof command.execute !== 'function'){
73+
throw new Error('command 对象必须实现 execute 方法');
74+
}
75+
command.execute();
76+
}
77+
}
78+
79+
setCommand(refreshMenuBarCommand);
80+
setCommand(addSubMenuCommand);
81+
setCommand(delSubMenuCommand);//报错Uncaught TypeError: undefined is not a function
82+
83+
84+
//typescript 版本
85+
interface Command {
86+
execute : Function;
87+
}
88+
class RefreshMenuBarCommand implements Command {
89+
constructor(){}
90+
91+
execute(){
92+
console.log('refresh menu page')
93+
}
94+
}
95+
96+
class AddSubMenuCommand implements Command {
97+
constructor(){}
98+
execute(){
99+
console.log('add sub menu')
100+
}
101+
}
102+
103+
class DelSubMenuCommand implements Command {
104+
constructor(){}
105+
}
106+
107+
var refreshMenuBarCommand = new RefreshMenuBarCommand();
108+
var addSubMenuCommand = new AddSubMenuCommand();
109+
var delSubMenuCommand = new DelSubMenuCommand();
110+
111+
refreshMenuBarCommand.execute();
112+
addSubMenuCommand.execute();
113+
delSubMenuCommand.execute();//输出:Uncaught TypeError: undefined is not a function

0 commit comments

Comments
 (0)