简介
桥接模式可将一系列严密相干的、程度等级的类,转变为组合关系,造成垂直等级关系。
如抽象类 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多平台公布