switch(источник)
case "sms":
answerProvider = new SmsAnswerProvider();
answerProvider.sendAnswer("Hello world")!
break;
case "email":
answerProvider = new EmailAnswerProvider();
answerProvider.sendAnswer("Hello world")!
break;
interface SenderInterface
{
public function sendAnswer(string $message): void;
public function supports(string $type): bool;
}
class EmailSender implements SenderInterface
{
public function sendAnswer(string $message): void
{
// тут отправляете сообщение
}
public function supports(string $type): bool
{
return 'email' === $type;
}
}
class SmsSender implements SenderInterface
{
public function sendAnswer(string $message): void
{
// тут отправляете сообщение
}
public function supports(string $type): bool
{
return 'sms' === $type;
}
}
class SenderAggregate
{
private $providers;
public function __construct(SenderInterface ...$providers)
{
$this->providers = $providers
}
public function send(string $type, string $message)
{
foreach ($this->providers as $provider) {
if ($provider->supports($type) {
return $provider->sendAnswer($message);
}
}
throw Exception;
}
}
class UserData {
/**
* @readonly
* @var string
*/
public $source;
public function __construct(string $source)
{
$this->source = $source;
}
}
class NoSupportingSenderFound extends \Exception {}
class AnswerTransportError extends \Exception {}
interface AnswerSender {
public function supportSource(string $source): bool;
/**
* @throws AnswerTransportError
*/
public function sendAnswer(string $answer): void;
}
class AnswerSenderFacade
{
/**
* @var AnswerSender[]
*/
private $senders = [];
public function __construct(AnswerSender ... $answerSenders)
{
$this->senders = $answerSenders;
}
/**
* @throws AnswerTransportError
* @throws NoSupportingSenderFound
*/
public function sendAnswer(UserData $userData, string $answer)
{
foreach ($this->senders as $sender) {
if($sender->supportSource($userData->source)) {
$sender->sendAnswer($answer);
return;
}
}
throw new NoSupportingSenderFound("...");
}
}
class Registry<T extends RegistryEntry> {
private Map<string, T> registries = new HashMap();
public void register(T entry) {}
public T find(string registryName) {}
}
class RegistryEntry {
public string registryName;
}
class AnswerProviderRegistry<AnswerProviderRegistryEntry> extends Registry {}
class AnswerProviderRegistryEntry<T extends IAnswerProvider> extends RegistryEntry {
abstract public T create();
}
class SmsAnswerProviderRegistryEntry<SmsAnswerProvider> extends AnswerProviderRegistryEntry {
constructor() {
this.registryName = "sms";
}
public SmsAnswerProvider create() {
return new SmsAnswerProvider();
}
}