Created
April 24, 2015 10:35
-
-
Save harunyasar/09a4ead847d2506c9554 to your computer and use it in GitHub Desktop.
PHP Design Patterns: Factory 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 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