Skip to content

Design patterns with Spring Boot

Somkiat Puisungnoen edited this page Sep 5, 2026 · 2 revisions

Design patterns with Spring Boot

1. Factory Method

  • Payment channels
    • Credit card
    • Debit card
    • Bank transfer
    • Prompt pay

Payment Processor

public interface PaymentProcessor {
    void process(Payment payment);
}

class CreditCardProcessor implements PaymentProcessor {
    @Override
    public void process(Payment payment) {

    }
}

class PromptPaymentProcessor implements PaymentProcessor {
    @Override
    public void process(Payment payment) {

    }
}

Payment Factory

@Component
public class PaymentFactory {

    private Map<String, PaymentProcessor> payments = new HashMap<>();
    public PaymentFactory() {
        payments.put("cc", new CreditCardProcessor());
        payments.put("pp", new PromptPaymentProcessor());
    }

    public PaymentProcessor getPaymentProcessor(String type) {
        return payments.get(type);
    }


}

Payment Service

@Service
public class PaymentService {

    @Autowired
    private PaymentFactory paymentFactory;

    public void process(String type, Payment payment) {
        paymentFactory.getPaymentProcessor(type).process(payment);
    }
}

2. Template method

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserCreateService extends  BaseService<UserRequest, UserResponse> {

    @Override
    @Transactional
    void doProcess(UserRequest userRequest, UserResponse userResponse) {
    }

}

record UserRequest(String username, String password) {
}
record UserResponse(String username, String password) {}


abstract class BaseService<Req, Res> {
    abstract void doProcess(Req req, Res res);
    public void process(Req req, Res res) {
    }
}

Clone this wiki locally