首页 PHP 正文
258

设计模式之桥接模式

      如果说某个系统能够从多个角度来进行分类,且每一种分类都可能会变化,那么我们需要做的就是将这多个角度分离出来,使得他们能独立变化,减少他们之间的耦合,这个分离过程就使用了桥接模式。所谓桥接模式就是将抽象部分和实现部分隔离开来,使得他们能够独立变化。
    桥接模式将继承关系转化成关联关系,封装了变化,完成了解耦,减少了系统中类的数量,也减少了代码量。
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();
抽象部分持有一个私有的实现对象。实现部分可以自由地扩展不同的实现类,同时抽象部分也可以有若干子类,这些子类可以自由地决定使用哪个实现类。
打个比方,时装周的模特服装展示,模特分为男模特与女模特,同时服装类型有春装、夏装。如果不用桥接模式,我们要创建以下类:春装男模、春装女模、夏装男模、夏装女模。如果要再加一个冬装,那么又得再添加两个类:冬装男模和冬装女模。这显然是有比较大的代码冗余。
利用桥接模式,我们将模特与服装分开,模特类派生两个子类:男模特和女模特。服装类派生两个子类:春装和夏装。模特类中有私有属性来引用服装对象。这样,模特与服装通过组合建立起了联系,同时各自可以再扩展各自的子类,也就是所说的,两个维度各自变化,互不影响。

正在加载评论...