实现适配器模式示例
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
实例
|
||||
汤宝宝有一个苹果手机,手机原配lightning接口,为了连接Type-C接口的充电器,他需要一个转换器(适配器)来实现这个功能。
|
||||
*/
|
||||
|
||||
// 充电器类
|
||||
class Charger {
|
||||
connect(typec: TypeCInterface) {
|
||||
typec.typeCCharging();
|
||||
console.log("手机开始充电!\n");
|
||||
}
|
||||
}
|
||||
|
||||
// Type-C充电接口的接口
|
||||
interface TypeCInterface {
|
||||
typeCCharging(): void;
|
||||
}
|
||||
|
||||
// 具体实现类
|
||||
class TypeC implements TypeCInterface {
|
||||
typeCCharging(): void {
|
||||
console.log("Type-C接口连接中...");
|
||||
}
|
||||
}
|
||||
|
||||
class Lightning {
|
||||
lightningCharging(): void {
|
||||
console.log("Lightning接口连接中...");
|
||||
}
|
||||
}
|
||||
|
||||
// 适配器类
|
||||
class LightningToTypeCAdapter implements TypeCInterface {
|
||||
private lightning: Lightning;
|
||||
constructor(lightning: Lightning) {
|
||||
this.lightning = lightning;
|
||||
}
|
||||
typeCCharging(): void {
|
||||
console.log("Type-C适配器转换中...")
|
||||
this.lightning.lightningCharging();
|
||||
}
|
||||
}
|
||||
|
||||
(function () {
|
||||
const charger = new Charger();
|
||||
|
||||
console.log("============= 适配器模式 =============");
|
||||
|
||||
console.log("使用Type-C充电器给小米手机充电:");
|
||||
const typec = new TypeC();
|
||||
charger.connect(typec);
|
||||
|
||||
console.log("使用Lightning接口转换器给苹果手机充电:");
|
||||
const lightning = new Lightning();
|
||||
const adapter = new LightningToTypeCAdapter(lightning);
|
||||
charger.connect(adapter);
|
||||
|
||||
console.log("=========== 适配器模式结束 ===========");
|
||||
})();
|
||||
Reference in New Issue
Block a user