Skip to content

Instantly share code, notes, and snippets.

@kauanmocelin
Created October 22, 2024 12:08
Show Gist options
  • Save kauanmocelin/a07a768b9077e17029839ab653524bf6 to your computer and use it in GitHub Desktop.
Save kauanmocelin/a07a768b9077e17029839ab653524bf6 to your computer and use it in GitHub Desktop.
Strategy and Factory com EnumMap
public class PaymentFactory {
private static final Map<PaymentType, PaymentStrategy> strategies = new EnumMap<>(PaymentType.class);
static {
strategies.put(PaymentType.CREDIT_CARD, new CreditCardPayment());
strategies.put(PaymentType.DEBIT_CARD, new DebitCardPayment());
strategies.put(PaymentType.CRYPTO, new CryptoPayment());
}
public static PaymentStrategy getPaymentStrategy(PaymentType paymentType) {
PaymentStrategy strategy = strategies.get(paymentType);
if (Objects.isNull(strategy))
throw new IllegalArgumentException("Strategy not found");
return strategy;
}
}
public class PaymentService {
public void processPayment(PaymentRequest request) {
// Don't forget to check objects if null!
if (Objects.isNull(request) || Objects.isNull(request.getPaymentType())
throw new IllegalArgumentException("Request can not be null!");
PaymentStrategy strategy = PaymentFactory.getPaymentStrategy(request.getPaymentType());
strategy.pay(request);
}
}
public interface PaymentStrategy {
void pay(PaymentRequest request);
}
public class CreditCardPayment implements PaymentStrategy {
@Override
public void pay(PaymentRequest request) {
System.out.println("Processing $type payment".replace("$type", String.valueOf(request.getPaymentType())));
}
}
public class DebitCardPayment implements PaymentStrategy {
@Override
public void pay(PaymentRequest request) {
System.out.println("Processing $type payment".replace("$type", String.valueOf(request.getPaymentType())));
}
}
public class CryptoPayment implements PaymentStrategy {
@Override
public void pay(PaymentRequest request) {
System.out.println("Processing $type payment".replace("$type", String.valueOf(request.getPaymentType())));
}
}
public enum PaymentType {
CREDIT_CARD,
DEBIT_CARD,
CRYPTO
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment