Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save harunyasar/09a4ead847d2506c9554 to your computer and use it in GitHub Desktop.
Save harunyasar/09a4ead847d2506c9554 to your computer and use it in GitHub Desktop.
PHP Design Patterns: Factory Pattern
<?php
interface Dog
{
public function speak ();
}
class Poodle implements Dog
{
public function speak()
{
echo "The poodle says \"arf\"\n";
}
}
class Rottweiler implements Dog
{
public function speak()
{
echo "The Rottweiler says (in a very deep voice) \"WOOF!\"\n";
}
}
class SiberianHusky implements Dog
{
public function speak()
{
echo "The husky says \"Dude, what's up?\"\n";
}
}
class DogFactory
{
public function getDog($criteria)
{
if ( $criteria == "small" )
return new Poodle();
else if ( $criteria == "big" )
return new Rottweiler();
else if ( $criteria == "working" )
return new SiberianHusky();
return null;
}
}
$dogFactory = new DogFactory();
$dog = $dogFactory->getDog("small");
$dog->speak();
$dog = $dogFactory->getDog("big");
$dog->speak();
$dog = $dogFactory->getDog("working");
$dog->speak();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment