Bridge Pattern

機能(function, feature, facility)と実装(implementation)を分ける。
あるクラスに対して、異なる実装が必要な場合に有効な設計手段。


実装の基底クラスをbridgeによって結びつける。bridgeはデレゲーションによって実現される。
そして、機能拡張は浅いほど良い。

<?php
 class Display{
  protected $impl;//<-- ブリッジ
  function __construct($impl){
    $this->impl = $impl;
  }
   
  function open(){ //<--DisplayクラスのAPI. ブリッジを通じて実装される
    $this->impl->raw_open();
  }
  function content(){ //<--DisplayクラスのAPI. ブリッジを通じて実装される
    $this->impl->raw_content();
  }
  function close(){ //<--DisplayクラスのAPI. ブリッジを通じて実装される
    $this->impl->raw_close();
  }
  final function render(){ //<--- 機能拡張しない(final method)
    $this->open();
    $this->content();
    $this->close();
  }
}

abstract class DisplayImpl{ //<-- 実装の基底クラス
  abstract function raw_open();
  abstract function raw_content();
  abstract function raw_close();
}

class SomeDisplayImpl extends DisplayImpl{ //<-- Displayの実装
  function raw_open(){
    
    
  }
  function raw_content(){
    
  }
  function raw_close(){
    
  }
}

class AnotherDisplayImpl extends DisplayImpl{//<--さらに別のDisplayの実装
  function raw_open(){
    
  }
  function raw_content(){
    
  }
  function raw_close(){
    
  }
}

class CountDisplay extends Display{ //<-- Displayクラスの拡張クラス
  function multi_render($times){
    $this->open();
    for($i = 0;$i< $times;$i++){
      $this->render();
    }
  }
}

$impl_x = new SomeDisplayImpl();
$impl_y = new AnotherDisplayImpl();
$impl_z = new AnotherDisplayImpl();
$disp_a = new Display($impl_x);
$disp_b = new Display($impl_y);
$disp_c = new CountDisplay($impl_z);

$disp_a->render();
$disp_b->render();
$disp_c->multi_render(4);

?>