Skip to content

Instantly share code, notes, and snippets.

@DeCarvalhoBruno
Created May 16, 2015 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DeCarvalhoBruno/4cee0ec3f86004242bc8 to your computer and use it in GitHub Desktop.
Save DeCarvalhoBruno/4cee0ec3f86004242bc8 to your computer and use it in GitHub Desktop.
Specializing classes on the fly with the Decorator design pattern
/**
* The contract mapping out some basic attributes
* that should be visible in all citizen classes
*
**/
interface IAmACitizen
{
public function getName();
public function getAddress();
public function getOccupation();
}
/**
* Our main citizen class
*/
class EuropeanCitizen implements IAmACitizen
{
protected $occupation;
protected $name;
protected $address;
function __construct( $occupation, $name, $address )
{
$this->occupation = $occupation;
$this->name = $name;
$this->address = $address;
}
public function getAddress()
{
return $this->address;
}
public function getOccupation()
{
return $this->occupation;
}
public function getName()
{
return $this->name;
}
}
class GermanCitizen
{
public function germanSpecificAttribute()
{
}
}
interface ICanDoWork
{
public function doWork();
}
abstract class EuropeanWorkerStereotype implements ICanDoWork
{
public function __construct( IAmACitizen $citizen )
{
$this->citizen = $citizen;
}
public function getAddress()
{
return $this->citizen->getAddress();
}
public function getOccupation()
{
return $this->citizen->getOccupation();
}
public function getName()
{
return $this->citizen->getName();
}
}
class GermanWorkerStereotype extends EuropeanWorkerStereotype
{
public function doWork()
{
return $this->makeCarsForEurope();
}
public function makeCarsForEurope()
{
return "BMW, Volkswagen, Audi...";
}
}
class GreekWorkerStereotype extends EuropeanWorkerStereotype
{
public function doWork()
{
return $this->lazeAllDay();
}
public function lazeAllDay()
{
return "ZZZZZZZZ";
}
}
class FrenchWorkerStereotype extends EuropeanWorkerStereotype
{
public function doWork()
{
return $this->goOnStrike( null, 5 );
}
public function goOnStrike( $reason = null, $numberOfWeeks )
{
return "What do we want? I don't know! When do we want it? Now!";
}
}
class DisplayWorker
{
public static function display( EuropeanWorkerStereotype $worker )
{
echo $worker->getName() . "<br/>";
echo $worker->getAddress() . "<br/>";
echo $worker->doWork() . "<br/>";
}
}
$worker = new EuropeanCitizen( "W", "X", "Y" );
$needAGreekWorker = true;
if ($needAGreekWorker) {
DisplayWorker::display( new GreekWorkerStereotype( $worker ) );
}
@DeCarvalhoBruno
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment