// 业务领域层
public class Customer {
private String id;
private String name;
private String email;
// 构造函数、getter和setter方法
@Override
public String toString() {
return "Customer{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", email='" + email + '\'' +
'}';
}
}
public class CustomerService {
private Repository<Customer> customerRepository;
public CustomerService(Repository<Customer> customerRepository) {
this.customerRepository = customerRepository;
}
public Customer findCustomerById(String id) {
return customerRepository.findById(id).orElse(null);
}
public Customer createCustomer(Customer customer) {
return customerRepository.save(customer);
}
}
// 应用服务层
public class CustomerApplicationService {
private CustomerRepository customerRepository;
private CustomerService customerService;
public CustomerApplicationService(CustomerRepository customerRepository, CustomerService customerService) {
this.customerRepository = customerRepository;
this.customerService = customerService;
}
public Customer findCustomerById(String id) {
return customerRepository.findById(id).orElse(null);
}
public Customer createCustomer(String name, String email) {
Customer customer = new Customer();
customer.setName(name);
customer.setEmail(email);
return customerService.createCustomer(customer);
}
}
// 基础设施层
@Repository
public class InMemoryCustomerRepository implements CustomerRepository {
private List<Customer> customers;
public InMemoryCustomerRepository() {
customers = new ArrayList<>();
}
@Override
public Optional<Customer> findById(String id) {
return Optional.ofNullable(customers.stream()
.filter(customer -> customer.getId().equals(id))
.findFirst()
.orElse(null));
}
@Override
public Customer save(Customer customer) {
customers.add(customer);
return customer;
}
}
// 技术框架层
public interface CustomerRepository {
Optional<Customer> findById(String id);
Customer save(Customer customer);
}
// 用户界面层
@Component
public class CustomerController {
private CustomerApplicationService customerApplicationService;
@Autowired
public CustomerController(CustomerApplicationService customerApplicationService) {
this.customerApplicationService = customerApplicationService;
}
@GetMapping("/customer/{id}")
public String findCustomerById(@PathVariable String id, Model model) {
Customer customer = customerApplicationService.findCustomerById(id);
model.addAttribute("customer", customer);
return "customer-details";
}
@PostMapping("/customer")
public String createCustomer(@RequestParam String name, @RequestParam String email, Model model) {
Customer customer = customerApplicationService.createCustomer(name, email);
model.addAttribute("customer", customer);
return "customer-created";
}
}
这是一个简单的领域驱动开发示例代码,包含业务领域层的Customer实体和CustomerService服务,应用服务层的CustomerApplicationService,基础设施层的InMemoryCustomerRepository,技术框架层的CustomerRepository接口,以及用户界面层的CustomerController控制器。