[Php design patterns] bridge mode

 Definition:
  The abstraction and separation, so that they may be varied independently. It is achieved by a combination relationship instead of inheritance, and abstraction implemented to reduce the dimensions of the two variable degree of coupling.

 Role:
  abstraction (Abstraction) roles: the definition of abstract class and contains a reference to the realization of the object.
  Extended abstract (Refined Abstraction) roles: the role of abstraction is a subclass, implement the business methods in the parent class, and through a combination of methods to achieve business relations calling role.
  Realization of (Implementor) roles: defining the role of the realization of the interface for extended abstract role call.
  Concrete realization of (Concrete Implementor) role: to achieve given the role of a specific implementation of the interface.

  For example:

  Car divided into many (cars, buses), and each car will run on different roads (streets, highways), if you use inheritance way we can achieve these scenarios
  but that to do so would make the code becomes scalable line is poor, but it is not the same use bridge mode

abstract class Road{
    public $car;
    public function __construct(Car $car){
        $this->car = $car;
    }
    public abstract function run();
}

class SpeedWay extends Road{
    public function run(){
        echo $this->car->name." run on SpeedWay\n";
    }
}

class Street extends Road{
    public function run(){
        echo $this->car->name." run on Street\n";
    }
}

abstract class Car{
    public $name;
}

class SmallCar extends Car{
    public function __construct(){
        $this->name = "SmallCar";
    }
}

class Bus extends Car{
    public function __construct(){
        $this->name = "Bus";
    }
}

$small_car = new SmallCar();
$SpeedWay = new SpeedWay($small_car);
$SpeedWay->run();

$bus = new Bus();
$Street = new Street($bus);
$Street->run();

  scenes to be used:

  When there are two independent dimensions a class change, and these two dimensions need to be extended.
  When a system does not want to use inheritance or as a multi-level inheritance led to a sharp increase in the number of system classes.
  When a system needs to add more flexibility between abstract and concrete role role member.




Guess you like

Origin www.cnblogs.com/itsuibi/p/10954306.html