Skip to content

Instantly share code, notes, and snippets.

@hastinbe
Created September 13, 2019 01:49
Show Gist options
  • Save hastinbe/3976324494a01ff408b67c528c3037d5 to your computer and use it in GitHub Desktop.
Save hastinbe/3976324494a01ff408b67c528c3037d5 to your computer and use it in GitHub Desktop.
Decorator Pattern Example #php #design-patterns #decorator-pattern
<?php
interface IGreeting
{
public function greeting();
}
abstract class GreetingDecorator implements IGreeting
{
protected $greeter;
public function __construct(IGreeting $greeter)
{
$this->greeter = $greeter;
}
public function greeting()
{
if ($this->greeter instanceof IGreeting)
{
$this->greeter->greeting();
}
}
}
class HelloGreeting implements IGreeting
{
public function greeting()
{
echo "Hello, \n";
}
}
class ThanksgivingGreeting extends GreetingDecorator
{
public function greeting()
{
parent::greeting();
echo "Happy Thanksgiving!\n";
}
}
class ChristmasGreeting extends GreetingDecorator
{
public function greeting()
{
parent::greeting();
echo "Merry Christmas!\n";
}
}
$greeter = new ThanksgivingGreeting(new HelloGreeting);
$greeter->greeting();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment