Created
June 15, 2017 19:16
-
-
Save tkouleris/d0e768d65e0e192605e618d259850ac1 to your computer and use it in GitHub Desktop.
Builder Design Pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| class Car{ | |
| private $doors; | |
| private $seats; | |
| private $color; | |
| public function __construct(){ | |
| echo "new Car object\r\n"; | |
| } | |
| public function getColor(){ | |
| return $this->color; | |
| } | |
| public function getDoors(){ | |
| return $this->doors; | |
| } | |
| public function getSeats(){ | |
| return $this->seats; | |
| } | |
| public function setColor($color){ | |
| $this->color = $color; | |
| } | |
| public function setDoors($doors){ | |
| $this->doors = $doors; | |
| } | |
| public function setSeats($seats){ | |
| $this->seats = $seats; | |
| } | |
| } | |
| class CarBuilder{ | |
| private $carInstance; | |
| public function __construct(){ | |
| $this->carInstance = new Car(); | |
| } | |
| public function setDoors($doors){ | |
| $this->carInstance->setDoors($doors); | |
| } | |
| public function setSeats($seats){ | |
| $this->carInstance->setSeats($seats); | |
| } | |
| public function setColor($color){ | |
| $this->carInstance->setColor($color); | |
| } | |
| public function getDoors(){ | |
| return $this->carInstance->getDoors(); | |
| } | |
| public function getSeats(){ | |
| return $this->carInstance->getSeats(); | |
| } | |
| public function getColor(){ | |
| return $this->carInstance->getColor(); | |
| } | |
| } | |
| class CarDirector{ | |
| private $carBuildInstance; | |
| public function __construct(CarBuilder $carBuilder){ | |
| $this->carBuildInstance = $carBuilder; | |
| } | |
| public function buildCar(){ | |
| $this->carBuildInstance->setDoors(4); | |
| $this->carBuildInstance->setSeats(5); | |
| $this->carBuildInstance->setColor('Black'); | |
| } | |
| public function getCar(){ | |
| echo 'Your car is ready.'.' You have a '.$this->carBuildInstance->getColor().' car with '.$this->carBuildInstance->getDoors().' doors and '.$this->carBuildInstance->getSeats().' seats.'; | |
| } | |
| } | |
| //Client | |
| echo "\r\n------- Builder Pattern ---\r\n"; | |
| $CarBuild = new CarBuilder(); | |
| $CarDir = new CarDirector($CarBuild); | |
| $CarDir->buildCar(); | |
| $CarDir->getCar(); | |
| echo "\r\n"; | |
| echo "\r\n----- No Builder Pattern ---\r\n"; | |
| $Car = new Car(); | |
| $Car->setColor("Red"); | |
| $Car->setDoors(2); | |
| $Car->setSeats(2); | |
| echo 'Your other car is a '. $Car->getColor().' car with '.$Car->getDoors().' doors and '.$Car->getSeats().' seats.'; | |
| echo "\r\n"; | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment