接口(interface)的定义:
1.对象的类型 c 结构体 封装了多个字段
2.行为的契约 java 封装抽象的行为(方法或函数的声明)
USB接口:
interface USB{
/**
* 插入
*/
plug():string;
pull():string;
}
Mouse类:
class Mouse implements USB {
pull(): string {
return "鼠标已断开";
}
plug(): string {
return "鼠标已连接";
}
}
Keyboard类:
class Keyboard implements USB {
pull(): string {
return "键盘已断开";
}
plug(): string {
return "键盘已连接";
}
}
PC类:
class PC {
// 属性依赖
// 参数依赖
// 依赖接口
// 多个USB接口
usbs:Array<USB>;
constructor() {
this.usbs=new Array();
}
/**
* 接入一个usb设备
* @param usb
*/
plugUSB(usb:USB){
if(usb){
// usb.plug();
console.log( usb.plug());
this.usbs.push(usb);
}
}
shutdown():void{
console.log(`PC shotdown`);
// 关机时,所有usb设备自动断开
for (const u of this.usbs) {
console.log( u.pull());
}
this.usbs.splice(0);
}
}
Superman类:
class SuperMan implements USB {
plug(): string {
return "超人连接";
}
pull(): string {
return "超人离开" ;
}
}
测试代码:
let pc=new PC();
pc.plugUSB(new Mouse());
pc.plugUSB(new Keyboard());
pc.plugUSB(new SuperMan());
pc.shutdown();
输出结果:
键盘已连接
超人连接
PC shotdown
鼠标已断开
键盘已断开
超人离开
来源:CSDN
作者:正在路上的小白
链接:https://blog.csdn.net/weixin_44364444/article/details/104212705