适配器模式(Adapter Pattern)是一种结构型设计模式,它允许将一个类的接口转换成客户端所期望的另一个接口形式,从而使得原本因接口不兼容而无法一起工作的那些类能够一起工作。
以下是一个对象适配器的示例:
// 目标接口
class Target {
request() {
return "Target: The default target's behavior.";
}
}
// 被适配者
class Adaptee {
specificRequest() {
return ".eetpadA eht fo roivaheb laicepS";
}
}
// 适配器
class Adapter extends Target {
constructor(adaptee) {
super();
this.adaptee = adaptee;
}
request() {
const result = this.adaptee.specificRequest().split('').reverse().join('');
return `Adapter: (TRANSLATED) ${result}`;
}
}
// 客户端代码
function clientCode(target) {
console.log(target.request());
}
const adaptee = new Adaptee();
const adapter = new Adapter(adaptee);
clientCode(adapter); // 输出: Adapter: (TRANSLATED) Specific behavior of the Adaptee.
通过理解适配器模式的基本概念和应用场景,你可以更好地在项目中使用它来解决接口不兼容的问题。