Skip to content

桥接模式

桥接模式(Bridge Pattern)是一种结构型设计模式,它旨在将抽象部分实现部分分离,使得它们可以独立地变化。在TypeScript中,桥接模式通过接口、抽象类和具体实现类来实现这种分离。

核心思想

桥接模式主要包含以下几个角色:

  1. 抽象类(Abstraction):充当桥接类,定义出该角色的行为,同时保存一个对实现化角色的引用。
  2. 扩展抽象类(RefinedAbstraction):是抽象类的子类,进一步细化抽象类的行为。
  3. 实现化接口(Implementor):行为实现化的接口,定义了实现化角色的行为。
  4. 具体实现类(ConcreteImplementor):行为的具体实现类,实现了实现化接口。

代码实现:

typescript
// 定义品牌接口
interface Brand {
    open(): void;
    close(): void;
    call(): void;
}

// 实现小米品牌
class XiaoMi implements Brand {
    open(): void {
        console.log("小米手机开机了");
    }
    close(): void {
        console.log("小米手机关机了");
    }
    call(): void {
        console.log("小米手机打电话");
    }
}

// 实现Vivo品牌
class Vivo implements Brand {
    open(): void {
        console.log("Vivo手机开机了");
    }
    close(): void {
        console.log("Vivo手机关机了");
    }
    call(): void {
        console.log("Vivo手机打电话");
    }
}

// 定义手机抽象类
abstract class Phone {
    protected brand: Brand;

    constructor(brand: Brand) {
        this.brand = brand;
    }

    protected open(): void {
        this.brand.open();
    }

    protected close(): void {
        this.brand.close();
    }

    protected call(): void {
        this.brand.call();
    }
}

// 定义折叠式手机类
class FoldedPhone extends Phone {
    open(): void {
        super.open();
        console.log("折叠样式手机");
    }

    close(): void {
        super.close();
        console.log("折叠样式手机");
    }

    call(): void {
        super.call();
        console.log("折叠样式手机");
    }
}

// 定义直立式手机类
class UpRightPhone extends Phone {
    open(): void {
        super.open();
        console.log("直立式样式手机");
    }

    close(): void {
        super.close();
        console.log("直立式样式手机");
    }

    call(): void {
        super.call();
        console.log("直立式样式手机");
    }
}

// 创建折叠式小米手机
let phone = new FoldedPhone(new XiaoMi());
phone.open();
phone.call();
phone.close();

// 创建折叠式Vivo手机
let phone2 = new FoldedPhone(new Vivo());
phone2.open();
phone2.call();
phone2.close();

// 创建直立式Vivo手机
let phone3 = new UpRightPhone(new Vivo());
phone3.open();
phone3.call();
phone3.close();