结构型设计模式-桥接(模块化) Bridge

发布时间 2023-09-06 13:36:25作者: 菜皮日记

简介

桥接模式可将一系列紧密相关的、水平等级的类,转变为组合关系,形成垂直等级关系。

如抽象类 Color、Shape,分别有 RedColor、BlueColor、CircleShape、SquareShape 的实现类,那么想创建红色方形,则可以将 Shape 类中持有 Color 引用,动态向 Shape 中注入 Color 实现即可。

否则分别实现 RedCircleShape、RedSquareShape、BlueCircleShape、BlueCircleShape 的话,假如再新增一个维度,实现类则需要修改,并新增很多实例。

桥接更直接的说就是组件化,模块化,让 A 中持有 B 的引用,B 可以随意调换,形成不同组合。

类图

角色

  • 抽象实体 A

    A 中包含实体 B 的引用

  • A 的具体实现

  • 抽象实体 B

  • B 的具体实现

类图

图中的 Remote 和 Device 中间,就是桥接。Remote 内部持有一个 Device 的引用:device。通过 set 不同的 device,实现 Remote 与 Device 的不同组合。

类图

代码

class Abstraction
{
    protected $implementation;

    public function __construct(Implementation $implementation)
    {
        $this->implementation = $implementation;
    }

    public function operation(): string
    {
        return "Abstraction: Base operation with:\n" .
            $this->implementation->operationImplementation();
    }
}

class ExtendedAbstraction extends Abstraction
{
    public function operation(): string
    {
        return "ExtendedAbstraction: Extended operation with:\n" .
            $this->implementation->operationImplementation();
    }
}

interface Implementation
{
    public function operationImplementation(): string;
}

class ConcreteImplementationA implements Implementation
{
    public function operationImplementation(): string
    {
        return "ConcreteImplementationA: Here's the result on the platform A.\n";
    }
}

class ConcreteImplementationB implements Implementation
{
    public function operationImplementation(): string
    {
        return "ConcreteImplementationB: Here's the result on the platform B.\n";
    }
}

function clientCode(Abstraction $abstraction)
{
    echo $abstraction->operation();
}

$implementation = new ConcreteImplementationA();
$abstraction = new Abstraction($implementation);
clientCode($abstraction);

$implementation = new ConcreteImplementationB();
$abstraction = new ExtendedAbstraction($implementation);
clientCode($abstraction);

output:

Abstraction: Base operation with:
ConcreteImplementationA: Here's the result on the platform A.
ExtendedAbstraction: Extended operation with:
ConcreteImplementationB: Here's the result on the platform B.

本文由mdnice多平台发布