Strategy Design Pattern
package org.example;
public interface Strategy {
void actionCommand();
}
package org.example;
public class AggressiveStrategy implements Strategy {
@Override
public void actionCommand() {
System.out.println("Aggressive strategy. Find and kill opponent.");
}
}
package org.example;
public class DefensiveStrategy implements Strategy {
@Override
public void actionCommand() {
System.out.println("Defensive strategy. Protect self and teammates.");
}
}
package org.example;
public class Player {
Strategy strategy;
String type;
public Player(String type) {
this.type = type;
}
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
public void action() {
System.out.println("Player: " + this.type);
strategy.actionCommand();
}
}
Another example:
package org.example.example2;
public interface PaymentStrategy {
void pay(double amount);
}
package org.example.example2;
public class PayPalPayment implements PaymentStrategy {
@Override
public void pay(double amount) {
System.out.println("Оплачено " + amount + " через PayPal.");
}
}
package org.example.example2;
public class CryptoPayment implements PaymentStrategy {
@Override
public void pay(double amount) {
System.out.println("Оплачено " + amount + " криптовалютой.");
}
}
package org.example.example2;
public class CreditCardPayment implements PaymentStrategy {
@Override
public void pay(double amount) {
System.out.println("Оплачено " + amount + " с помощью кредитной карты.");
}
}
package org.example.example2;
public class PaymentContext {
private PaymentStrategy paymentStrategy;
public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
this.paymentStrategy = paymentStrategy;
}
public void executePayment(double amount) {
if (paymentStrategy == null) {
throw new IllegalStateException("Стратегия оплаты не установлена!");
}
paymentStrategy.pay(amount);
}
}
package org.example.example2;
public class Main {
public static void main(String[] args) {
PaymentContext context = new PaymentContext();
context.setPaymentStrategy(new CreditCardPayment());
context.executePayment(100.0);
context.setPaymentStrategy(new PayPalPayment());
context.executePayment(50.0);
context.setPaymentStrategy(new CryptoPayment());
context.executePayment(200.0);
}
}
Using Strategy and Factory together:
package org.example.example2;
public class PaymentStrategyFactory {
public static PaymentStrategy getPaymentStrategy(String type) {
switch (type.toLowerCase()) {
case "card":
return new CreditCardPayment();
case "paypal":
return new PayPalPayment();
case "crypto":
return new CryptoPayment();
default:
throw new IllegalArgumentException("Неизвестный способ оплаты: " + type);
}
}
}
package org.example.example2;
public class StrategyFactoryExample {
public static void main(String[] args) {
PaymentStrategy paymentStrategy = PaymentStrategyFactory.getPaymentStrategy("paypal");
paymentStrategy.pay(100.0);
}
}
Комментарии
Отправить комментарий