Junior — Middle
158
Hoe implementeer je de keuze van de kortingsberekeningsmethode op basis van een specifieke gebruiker?
Bedrijven waar gevraagd werd
Алгоритмика
Antwoord van AI
sobes.tech AI
Для выбора метода расчета скидки в зависимости от конкретного пользователя в PHP можно использовать паттерн "Стратегия". Идея в том, чтобы определить разные классы расчета скидки и выбирать нужный в зависимости от свойств пользователя.
Пример:
interface DiscountStrategy {
public function calculate(float $price): float;
}
class VipDiscount implements DiscountStrategy {
public function calculate(float $price): float {
return $price * 0.8; // 20% скидка
}
}
class RegularDiscount implements DiscountStrategy {
public function calculate(float $price): float {
return $price * 0.95; // 5% скидка
}
}
class NoDiscount implements DiscountStrategy {
public function calculate(float $price): float {
return $price; // без скидки
}
}
class User {
public string $type; // например, 'vip', 'regular', 'guest'
public function __construct(string $type) {
$this->type = $type;
}
}
function getDiscountStrategy(User $user): DiscountStrategy {
switch ($user->type) {
case 'vip':
return new VipDiscount();
case 'regular':
return new RegularDiscount();
default:
return new NoDiscount();
}
}
// Использование
$user = new User('vip');
$strategy = getDiscountStrategy($user);
$finalPrice = $strategy->calculate(1000);
echo $finalPrice; // 800
Такой подход позволяет легко расширять логику скидок и поддерживать код.