桥接模式将继承关系转化成关联关系,封装了变化,完成了解耦,减少了系统中类的数量,也减少了代码量。
class Abstraction{ protected $implementor; public function SetImplementor(Implementor $implementor){ $this->implementor = $implementor; } public function Operation(){ $this->implementor->Operation(); } } class RefinedAbstraction extends Abstraction{ public function Operation(){ $this->implementor->Operation(); } } abstract class Implementor{ public abstract function Operation(); } class ConcreteImplementorA extends Implementor{ public function Operation(){ echo "ConcreteImplementorA was called<br>"; } } class ConcreteImplementorB extends Implementor{ public function Operation(){ echo "ConcreteImplementorB was called<br>"; } } $refinedAbstraction = new RefinedAbstraction(); $concreteImplementorA = new ConcreteImplementorA(); $refinedAbstraction->setImplementor($concreteImplementorA); $refinedAbstraction->Operation(); $concreteImplementorB = new ConcreteImplementorB(); $refinedAbstraction->setImplementor($concreteImplementorB); $refinedAbstraction->Operation();抽象部分持有一个私有的实现对象。实现部分可以自由地扩展不同的实现类,同时抽象部分也可以有若干子类,这些子类可以自由地决定使用哪个实现类。
打个比方,时装周的模特服装展示,模特分为男模特与女模特,同时服装类型有春装、夏装。如果不用桥接模式,我们要创建以下类:春装男模、春装女模、夏装男模、夏装女模。如果要再加一个冬装,那么又得再添加两个类:冬装男模和冬装女模。这显然是有比较大的代码冗余。
利用桥接模式,我们将模特与服装分开,模特类派生两个子类:男模特和女模特。服装类派生两个子类:春装和夏装。模特类中有私有属性来引用服装对象。这样,模特与服装通过组合建立起了联系,同时各自可以再扩展各自的子类,也就是所说的,两个维度各自变化,互不影响。