Last active
April 2, 2016 15:17
-
-
Save harunyasar/055e503d185a875e0e90 to your computer and use it in GitHub Desktop.
PHP Design Patterns: Decorator Pattern
This file contains 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 | |
interface Shape { | |
public function draw(); | |
} | |
class Rectangle implements Shape { | |
public function draw() { | |
echo "Shape: Rectangle\r\n"; | |
} | |
} | |
class Circle implements Shape { | |
public function draw() { | |
echo "Shape: Circle\r\n"; | |
} | |
} | |
abstract class ShapeDecorator implements Shape { | |
protected $decoratedShape; | |
public function ShapeDecorator(Shape $decoratedShape){ | |
$this->decoratedShape = $decoratedShape; | |
} | |
public function draw(){ | |
$this->decoratedShape->draw(); | |
} | |
} | |
class RedShapeDecorator extends ShapeDecorator { | |
protected $decoratedShape; | |
public function RedShapeDecorator(Shape $decoratedShape) { | |
$this->decoratedShape = $decoratedShape; | |
} | |
public function draw() { | |
$this->decoratedShape->draw(); | |
$this->setRedBorder($this->decoratedShape); | |
} | |
private function setRedBorder(Shape $decoratedShape){ | |
echo "Border Color: Red\r\n"; | |
} | |
} | |
$circle = new Circle(); | |
$rectangle = new Rectangle(); | |
$redCircle = new RedShapeDecorator($circle); | |
$redRectangle = new RedShapeDecorator($rectangle); | |
echo "Circle with normal border\r\n"; | |
$circle->draw(); | |
echo "\nCircle of red border\r\n"; | |
$redCircle->draw(); | |
echo "\nRectangle of red border\r\n"; | |
$redRectangle->draw(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment