Created
May 22, 2022 01:39
-
-
Save 77web/b2810d8b5465fc50cb61fba0538d34e3 to your computer and use it in GitHub Desktop.
継承でもいいかもしれないやつ
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 AnswerToゲームほしい implements AnswerStrategyInterface | |
{ | |
public function supports(string $ask): bool | |
{ | |
return $ask === 'ゲームほしい'; | |
} | |
public function answer(): string | |
{ | |
return 'だめ'; | |
} | |
} | |
class AnswerTo課金していい implements AnswerStrategyInterface | |
{ | |
public function supports(string $ask): bool | |
{ | |
return $ask === '課金していい?'; | |
} | |
public function answer(): string | |
{ | |
return 'だめ'; | |
} | |
} | |
class FallbackAnswer implements AnswerStrategyInterface | |
{ | |
public function supports(string $ask): bool | |
{ | |
return true; | |
} | |
public function answer(): string | |
{ | |
return 'うん'; | |
} | |
} | |
class AnswerResolver | |
{ | |
private array $answers; | |
public function __construct() | |
{ | |
$this->answers = [ | |
new AnswerTo課金していい(), | |
new AnswerToゲームほしい(), | |
new FallbackAnswer(), | |
]; | |
} | |
public function resolve(string $ask): AnswerStrategyInterface | |
{ | |
foreach ($this->answers as $strategy) { | |
if ($strategy->supports($ask)) { | |
return $strategy; | |
} | |
} | |
throw new \LogicException('答えが設定されてません'); | |
} | |
} | |
$寝てるときの私 = new AnswerResolver(); | |
$寝てるときの私->resolve('ご飯まだ?')->answer(); // うん | |
$寝てるときの私->resolve('ねえ聞いてる?')->answer(); // うん | |
$寝てるときの私->resolve('課金していい?')->answer(); // だめ | |
$寝てるときの私->resolve('ゲームほしい')->answer(); // だめ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment