1. DDD Layers
Presentation Layer -> REST Controller / UI
Application Layer -> Services coordinating use cases
Domain Layer -> Business logic (Entities, Value Objects, Aggregates, Domain Services)
Infrastructure Layer -> Database, Repositories
2. Example: Online Ordering System
Domain Layer
Entity: Customer
public class Customer {
private String id;
private String name;
public Customer(String id, String name) {
this.id = id;
this.name = name;
}
// getters
}
Value Object: Address
public class Address {
private String street;
private String city;
public Address(String street, String city) {
this.street = street;
this.city = city;
}
// getters
}
Aggregate: Order
import java.util.ArrayList;
import java.util.List;
public class Order {
private String id;
private Customer customer;
private List<String> items = new ArrayList<>();
public Order(String id, Customer customer) {
this.id = id;
this.customer = customer;
}
public void addItem(String item) {
items.add(item);
}
// getters
}
Domain Service: PaymentService
public class PaymentService {
public boolean processPayment(Order order) {
// Payment logic here
return true;
}
}
Infrastructure Layer
Repository Interface
public interface OrderRepository {
void save(Order order);
Order findById(String id);
}
Repository Implementation (In-Memory)
import java.util.HashMap;
import java.util.Map;
public class InMemoryOrderRepository implements OrderRepository {
private Map<String, Order> db = new HashMap<>();
public void save(Order order) {
db.put(order.getId(), order);
}
public Order findById(String id) {
return db.get(id);
}
}
Application Layer
import java.util.List;
public class OrderService {
private OrderRepository orderRepository;
private PaymentService paymentService;
public OrderService(OrderRepository orderRepository, PaymentService paymentService) {
this.orderRepository = orderRepository;
this.paymentService = paymentService;
}
public void placeOrder(Customer customer, List<String> items) {
Order order = new Order("1", customer);
items.forEach(order::addItem);
orderRepository.save(order);
paymentService.processPayment(order);
}
}
Presentation Layer
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
OrderRepository repo = new InMemoryOrderRepository();
PaymentService paymentService = new PaymentService();
OrderService orderService = new OrderService(repo, paymentService);
Customer customer = new Customer("C001", "John Doe");
orderService.placeOrder(customer, Arrays.asList("Item1", "Item2"));
System.out.println("Order placed successfully!");
}
}
✅ Key Points:
- Domain Layer → Business logic (
Order
,Customer
,PaymentService
) - Application Layer → Coordinates actions (
OrderService
) - Infrastructure Layer → Database or repositories (
InMemoryOrderRepository
) - Presentation Layer → User interface (
Main
in this example)