桥接器模式是一种结构型设计模式,旨在将抽象部分与实现部分分离,使它们可以独立变化而不相互影响。桥接器模式通过创建一个桥接接口,连接抽象和实现,从而使两者可以独立演化。
桥接器模式通常包括以下几个要素:
// 实现接口
class Implementor {
operationImpl() {
console.log("Implementor operation");
}
}
// 具体实现类A
class ConcreteImplementorA extends Implementor {
operationImpl() {
console.log("Concrete Implementor A operation");
}
}
// 具体实现类B
class ConcreteImplementorB extends Implementor {
operationImpl() {
console.log("Concrete Implementor B operation");
}
}
// 抽象类
class Abstraction {
constructor(implementor) {
this.implementor = implementor;
}
operation() {
console.log("Abstraction operation ->");
this.implementor.operationImpl();
}
}
// 扩充抽象类
class RefinedAbstraction extends Abstraction {
constructor(implementor) {
super(implementor);
}
operation() {
console.log("Refined Abstraction operation ->");
this.implementor.operationImpl();
}
}
// 客户端代码
const implementorA = new ConcreteImplementorA();
const implementorB = new ConcreteImplementorB();
const abstractionA = new RefinedAbstraction(implementorA);
const abstractionB = new RefinedAbstraction(implementorB);
abstractionA.operation(); // 输出:Refined Abstraction operation -> Concrete Implementor A operation
abstractionB.operation(); // 输出:Refined Abstraction operation -> Concrete Implementor B operation