Last active
December 16, 2015 01:09
-
-
Save a-suenami/5352611 to your computer and use it in GitHub Desktop.
オブジェクト指向っぽくFizzBuzzを解いてみる。
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 | |
class FizzBuzz | |
{ | |
private $n; | |
private $fizzSpec; | |
private $buzzSpec; | |
private $noFizzBuzzSpec; | |
public function __construct($n) | |
{ | |
$this->n = (int)$n; | |
$this->fizzSpec = new FizzSpecification(); | |
$this->buzzSpec = new BuzzSpecification(); | |
$this->noFizzBuzzSpec = new NoFizzBuzzSpecification(); | |
} | |
public function getN() | |
{ | |
return $this->n; | |
} | |
public function toString() | |
{ | |
if ($this->noFizzBuzzSpec->isSatisfiedBy($this)) return (string)$this->n; | |
$isFizz = $this->fizzSpec->isSatisfiedBy($this); | |
$fizz = Fizz::getInstance($isFizz); | |
$isBuzz = $this->buzzSpec->isSatisfiedBy($this); | |
$buzz = Buzz::getInstance($isBuzz); | |
return $fizz->toString() . $buzz->toString(); | |
} | |
} | |
interface SpecificationInterface | |
{ | |
function isSatisfiedBy(FizzBuzz $fizzbuzz); | |
} | |
class FizzSpecification implements SpecificationInterface | |
{ | |
function isSatisfiedBy(FizzBuzz $fizzbuzz) | |
{ | |
return $fizzbuzz->getN() % 3 === 0; | |
} | |
} | |
class BuzzSpecification implements SpecificationInterface | |
{ | |
function isSatisfiedBy(FizzBuzz $fizzbuzz) | |
{ | |
return $fizzbuzz->getN() % 5 === 0; | |
} | |
} | |
class NoFizzBuzzSpecification implements SpecificationInterface | |
{ | |
function isSatisfiedBy(FizzBuzz $fizzbuzz) | |
{ | |
$fizzSpec = new FizzSpecification(); | |
$buzzSpec = new BuzzSpecification(); | |
return !$fizzSpec->isSatisfiedBy($fizzbuzz) && !$buzzSpec->isSatisfiedBy($fizzbuzz); | |
} | |
} | |
interface FizzBuzzInterface | |
{ | |
public function toString(); | |
} | |
class Fizz implements FizzBuzzInterface | |
{ | |
public static function getInstance($isFizz) | |
{ | |
return $isFizz ? new Fizz() : new NullFizz(); | |
} | |
public function toString() | |
{ | |
return "Fizz"; | |
} | |
} | |
class NullFizz extends Fizz | |
{ | |
public function toString() | |
{ | |
return ""; | |
} | |
} | |
class Buzz implements FizzBuzzInterface | |
{ | |
public static function getInstance($isBuzz) | |
{ | |
return $isBuzz ? new Buzz() : new NullBuzz(); | |
} | |
public function toString() | |
{ | |
return "Buzz"; | |
} | |
} | |
class NullBuzz extends Buzz | |
{ | |
public function toString() | |
{ | |
return ""; | |
} | |
} | |
$fizzbuzz = array(); | |
for ($i = 1; $i <= 20; $i++) { | |
$fizzbuzz[$i] = new FizzBuzz($i); | |
echo sprintf("FizzBuzz(%d) = %s\n", $i, $fizzbuzz[$i]->toString()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment