Skip to content

Instantly share code, notes, and snippets.

@harunyasar
Last active April 2, 2016 15:17
Show Gist options
  • Save harunyasar/055e503d185a875e0e90 to your computer and use it in GitHub Desktop.
Save harunyasar/055e503d185a875e0e90 to your computer and use it in GitHub Desktop.
PHP Design Patterns: Decorator Pattern
<?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