registerUserメソッドから実際の登録処理を呼び出す想定ですが、国ごとに違うであろう登録処理をregisterUserメソッドが知らなければいけないことが問題となります。
<?php
class UserRegistration
{
public function registerUser(User $user): string
{
if ($user->getCountry() == 'JP') {
// 国内ユーザーの登録処理
return '国内ユーザー登録完了';
}
// 海外ユーザーの登録処理
return '海外ユーザー登録完了';
}
}
<?php
class User
{
private string $country;
public function setCountry(string $country): void
{
$this->country = $country;
}
public function getCountry(): string
{
return $this->country;
}
}
<?php
$user = new User();
$user->setCountry('JP');
$registration = new UserRegistration();
$result = $registration->registerUser($user);
echo $result;
この改善例では、UserRegistrationクラスは外部の条件に応じて異なる処理を知る必要がなくなり、ユーザー登録の具体的な処理はUserRegisterServiceインターフェースを実装する異なるクラスに分離されています。 これにより、UserRegistrationはユーザーの国に応じた適切な登録処理を提供するために、条件に制御されることなく、より柔軟で拡張可能なアーキテクチャを実現しています。
<?php
class UserRegistration
{
private UserRegisterService $userRegisterService;
public function __construct(UserRegisterService $userRegisterService)
{
$this->userRegisterService = $userRegisterService;
}
public function registerUser(User $user): string
{
$result = $this->userRegisterService->register($user);
return $result;
}
}
<?php
class JapaneseUserRegisterService implements UserRegisterService
{
public function register(User $user): string
{
// 国内ユーザーの登録処理
return '国内ユーザー登録完了';
}
}
<?php
class ForeignUserRegisterService implements UserRegisterService
{
public function register(User $user): string
{
// 海外ユーザーの登録処理
return '海外ユーザー登録完了';
}
}
<?php
interface UserRegisterService
{
public function register(User $user): string;
}
<?php
class User
{
private string $country;
public function setCountry(string $country): void
{
$this->country = $country;
}
public function getCountry(): string
{
return $this->country;
}
}
<?php
$user = new User();
$user->setCountry('JP');
$registration = new UserRegistration(new JapaneseUserRegisterService());
$result = $registration->registerUser($user);
echo $result;