图灵核心编程实战班 语法+函数+面向对象+并发编程与数据库全覆盖

egwegerhtyf · · 67 次点击 · · 开始浏览    

获课地址:666it.top/14062/ 图灵核心编程实战:从零构建完整电商订单系统 在编程学习的道路上,很多初学者都会遇到这样的困境:学习了大量理论知识,但面对实际项目时却不知从何下手。本文将通过一个完整的电商订单系统实战项目,带你深入理解核心编程概念,掌握项目开发全流程。 项目概述与设计 我们将构建一个基于Java的电商订单管理系统,包含用户管理、商品管理、订单处理等核心模块。系统采用分层架构设计,包括表现层、业务逻辑层和数据访问层。 首先,让我们定义系统的主要实体类: java // 用户实体类 public class User { private Long id; private String username; private String email; private String password; private String phone; private Date createTime; private Date updateTime; // 构造方法 public User() {} public User(String username, String email, String password) { this.username = username; this.email = email; this.password = password; this.createTime = new Date(); } // Getter和Setter方法 public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } @Override public String toString() { return "User{id=" + id + ", username='" + username + '\'' + ", email='" + email + '\'' + '}'; } } // 商品实体类 public class Product { private Long id; private String name; private String description; private BigDecimal price; private Integer stock; private String category; private Date createTime; // 构造方法、Getter和Setter public Product() {} public Product(String name, String description, BigDecimal price, Integer stock, String category) { this.name = name; this.description = description; this.price = price; this.stock = stock; this.category = category; this.createTime = new Date(); } // 省略其他Getter和Setter方法... // 检查库存是否充足 public boolean isStockSufficient(Integer quantity) { return this.stock >= quantity; } // 减少库存 public void decreaseStock(Integer quantity) { if (isStockSufficient(quantity)) { this.stock -= quantity; } else { throw new IllegalArgumentException("库存不足"); } } } // 订单实体类 public class Order { private Long id; private String orderNumber; private Long userId; private BigDecimal totalAmount; private String status; // PENDING, PAID, SHIPPED, COMPLETED, CANCELLED private String shippingAddress; private Date createTime; private Date updateTime; private List<OrderItem> orderItems; public Order() { this.orderItems = new ArrayList<>(); this.createTime = new Date(); this.status = "PENDING"; } // 计算订单总金额 public void calculateTotalAmount() { this.totalAmount = BigDecimal.ZERO; for (OrderItem item : orderItems) { this.totalAmount = this.totalAmount.add(item.getSubtotal()); } } // 添加订单项 public void addOrderItem(OrderItem item) { this.orderItems.add(item); calculateTotalAmount(); } // 省略其他Getter和Setter方法... } // 订单项实体类 public class OrderItem { private Long id; private Long orderId; private Long productId; private String productName; private BigDecimal unitPrice; private Integer quantity; private BigDecimal subtotal; public OrderItem() {} public OrderItem(Long productId, String productName, BigDecimal unitPrice, Integer quantity) { this.productId = productId; this.productName = productName; this.unitPrice = unitPrice; this.quantity = quantity; calculateSubtotal(); } // 计算小计 public void calculateSubtotal() { this.subtotal = unitPrice.multiply(BigDecimal.valueOf(quantity)); } // 省略Getter和Setter方法... } 数据访问层实现 接下来,我们实现数据访问层,这里使用Repository模式来管理数据的持久化操作: java // 泛型基础Repository接口 public interface BaseRepository<T, ID> { T save(T entity); Optional<T> findById(ID id); List<T> findAll(); void delete(ID id); T update(T entity); } // 用户Repository实现 public class UserRepository implements BaseRepository<User, Long> { private Map<Long, User> userStorage = new ConcurrentHashMap<>(); private AtomicLong idGenerator = new AtomicLong(1); @Override public User save(User user) { if (user.getId() == null) { user.setId(idGenerator.getAndIncrement()); } user.setUpdateTime(new Date()); userStorage.put(user.getId(), user); return user; } @Override public Optional<User> findById(Long id) { return Optional.ofNullable(userStorage.get(id)); } @Override public List<User> findAll() { return new ArrayList<>(userStorage.values()); } @Override public void delete(Long id) { userStorage.remove(id); } @Override public User update(User user) { if (userStorage.containsKey(user.getId())) { user.setUpdateTime(new Date()); userStorage.put(user.getId(), user); return user; } throw new IllegalArgumentException("用户不存在: " + user.getId()); } // 根据用户名查找用户 public Optional<User> findByUsername(String username) { return userStorage.values().stream() .filter(user -> user.getUsername().equals(username)) .findFirst(); } // 根据邮箱查找用户 public Optional<User> findByEmail(String email) { return userStorage.values().stream() .filter(user -> user.getEmail().equals(email)) .findFirst(); } } // 商品Repository实现 public class ProductRepository implements BaseRepository<Product, Long> { private Map<Long, Product> productStorage = new ConcurrentHashMap<>(); private AtomicLong idGenerator = new AtomicLong(1); @Override public Product save(Product product) { if (product.getId() == null) { product.setId(idGenerator.getAndIncrement()); } productStorage.put(product.getId(), product); return product; } @Override public Optional<Product> findById(Long id) { return Optional.ofNullable(productStorage.get(id)); } @Override public List<Product> findAll() { return new ArrayList<>(productStorage.values()); } @Override public void delete(Long id) { productStorage.remove(id); } @Override public Product update(Product product) { if (productStorage.containsKey(product.getId())) { productStorage.put(product.getId(), product); return product; } throw new IllegalArgumentException("商品不存在: " + product.getId()); } // 根据分类查找商品 public List<Product> findByCategory(String category) { return productStorage.values().stream() .filter(product -> product.getCategory().equalsIgnoreCase(category)) .collect(Collectors.toList()); } // 根据价格范围查找商品 public List<Product> findByPriceRange(BigDecimal minPrice, BigDecimal maxPrice) { return productStorage.values().stream() .filter(product -> product.getPrice().compareTo(minPrice) >= 0 && product.getPrice().compareTo(maxPrice) <= 0) .collect(Collectors.toList()); } } // 订单Repository实现 public class OrderRepository implements BaseRepository<Order, Long> { private Map<Long, Order> orderStorage = new ConcurrentHashMap<>(); private AtomicLong idGenerator = new AtomicLong(1); private AtomicLong orderNumberGenerator = new AtomicLong(100000); @Override public Order save(Order order) { if (order.getId() == null) { order.setId(idGenerator.getAndIncrement()); order.setOrderNumber(generateOrderNumber()); } order.setUpdateTime(new Date()); orderStorage.put(order.getId(), order); return order; } @Override public Optional<Order> findById(Long id) { return Optional.ofNullable(orderStorage.get(id)); } @Override public List<Order> findAll() { return new ArrayList<>(orderStorage.values()); } @Override public void delete(Long id) { orderStorage.remove(id); } @Override public Order update(Order order) { if (orderStorage.containsKey(order.getId())) { order.setUpdateTime(new Date()); orderStorage.put(order.getId(), order); return order; } throw new IllegalArgumentException("订单不存在: " + order.getId()); } // 生成订单号 private String generateOrderNumber() { return "ORD" + System.currentTimeMillis() + orderNumberGenerator.getAndIncrement(); } // 根据用户ID查找订单 public List<Order> findByUserId(Long userId) { return orderStorage.values().stream() .filter(order -> order.getUserId().equals(userId)) .sorted((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime())) .collect(Collectors.toList()); } // 根据状态查找订单 public List<Order> findByStatus(String status) { return orderStorage.values().stream() .filter(order -> order.getStatus().equals(status)) .collect(Collectors.toList()); } } 业务逻辑层实现 业务逻辑层负责处理复杂的业务规则和流程: java // 用户服务 public class UserService { private UserRepository userRepository; public UserService(UserRepository userRepository) { this.userRepository = userRepository; } // 用户注册 public User register(User user) { // 验证用户名是否已存在 if (userRepository.findByUsername(user.getUsername()).isPresent()) { throw new IllegalArgumentException("用户名已存在: " + user.getUsername()); } // 验证邮箱是否已存在 if (userRepository.findByEmail(user.getEmail()).isPresent()) { throw new IllegalArgumentException("邮箱已存在: " + user.getEmail()); } // 密码加密(这里使用简单加密,实际项目中应使用更安全的加密方式) String encryptedPassword = encryptPassword(user.getPassword()); user.setPassword(encryptedPassword); return userRepository.save(user); } // 用户登录 public User login(String username, String password) { User user = userRepository.findByUsername(username) .orElseThrow(() -> new IllegalArgumentException("用户不存在: " + username)); String encryptedPassword = encryptPassword(password); if (!user.getPassword().equals(encryptedPassword)) { throw new IllegalArgumentException("密码错误"); } return user; } // 密码加密 private String encryptPassword(String password) { // 实际项目中应使用BCrypt等安全加密方式 try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] digest = md.digest(password.getBytes()); return Base64.getEncoder().encodeToString(digest); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("密码加密失败", e); } } // 更新用户信息 public User updateUser(User user) { User existingUser = userRepository.findById(user.getId()) .orElseThrow(() -> new IllegalArgumentException("用户不存在: " + user.getId())); // 保留原有密码,如果不修改密码 if (user.getPassword() == null) { user.setPassword(existingUser.getPassword()); } else { user.setPassword(encryptPassword(user.getPassword())); } return userRepository.update(user); } } // 商品服务 public class ProductService { private ProductRepository productRepository; public ProductService(ProductRepository productRepository) { this.productRepository = productRepository; } // 添加商品 public Product addProduct(Product product) { validateProduct(product); return productRepository.save(product); } // 更新商品 public Product updateProduct(Product product) { validateProduct(product); Product existingProduct = productRepository.findById(product.getId()) .orElseThrow(() -> new IllegalArgumentException("商品不存在: " + product.getId())); return productRepository.update(product); } // 验证商品信息 private void validateProduct(Product product) { if (product.getName() == null || product.getName().trim().isEmpty()) { throw new IllegalArgumentException("商品名称不能为空"); } if (product.getPrice() == null || product.getPrice().compareTo(BigDecimal.ZERO) <= 0) { throw new IllegalArgumentException("商品价格必须大于0"); } if (product.getStock() == null || product.getStock() < 0) { throw new IllegalArgumentException("库存不能为负数"); } } // 根据ID获取商品 public Product getProductById(Long id) { return productRepository.findById(id) .orElseThrow(() -> new IllegalArgumentException("商品不存在: " + id)); } // 获取所有商品 public List<Product> getAllProducts() { return productRepository.findAll(); } // 根据分类获取商品 public List<Product> getProductsByCategory(String category) { return productRepository.findByCategory(category); } // 搜索商品 public List<Product> searchProducts(String keyword) { return productRepository.findAll().stream() .filter(product -> product.getName().toLowerCase().contains(keyword.toLowerCase()) || product.getDescription().toLowerCase().contains(keyword.toLowerCase())) .collect(Collectors.toList()); } // 检查库存 public boolean checkStock(Long productId, Integer quantity) { Product product = getProductById(productId); return product.isStockSufficient(quantity); } // 减少库存 public void decreaseStock(Long productId, Integer quantity) { Product product = getProductById(productId); product.decreaseStock(quantity); productRepository.update(product); } // 增加库存 public void increaseStock(Long productId, Integer quantity) { Product product = getProductById(productId); product.setStock(product.getStock() + quantity); productRepository.update(product); } } // 订单服务 public class OrderService { private OrderRepository orderRepository; private ProductService productService; private UserService userService; public OrderService(OrderRepository orderRepository, ProductService productService, UserService userService) { this.orderRepository = orderRepository; this.productService = productService; this.userService = userService; } // 创建订单 public Order createOrder(Long userId, Map<Long, Integer> productQuantities, String shippingAddress) { // 验证用户存在 userService.login("dummy", "dummy"); // 简单验证用户存在 Order order = new Order(); order.setUserId(userId); order.setShippingAddress(shippingAddress); // 添加订单项 for (Map.Entry<Long, Integer> entry : productQuantities.entrySet()) { Long productId = entry.getKey(); Integer quantity = entry.getValue(); Product product = productService.getProductById(productId); // 检查库存 if (!productService.checkStock(productId, quantity)) { throw new IllegalArgumentException("商品库存不足: " + product.getName()); } OrderItem orderItem = new OrderItem( productId, product.getName(), product.getPrice(), quantity ); order.addOrderItem(orderItem); // 减少库存 productService.decreaseStock(productId, quantity); } return orderRepository.save(order); } // 根据ID获取订单 public Order getOrderById(Long orderId) { return orderRepository.findById(orderId) .orElseThrow(() -> new IllegalArgumentException("订单不存在: " + orderId)); } // 获取用户的所有订单 public List<Order> getUserOrders(Long userId) { return orderRepository.findByUserId(userId); } // 更新订单状态 public Order updateOrderStatus(Long orderId, String status) { Order order = getOrderById(orderId); // 验证状态转换是否合法 validateStatusTransition(order.getStatus(), status); order.setStatus(status); order.setUpdateTime(new Date()); return orderRepository.update(order); } // 验证状态转换 private void validateStatusTransition(String currentStatus, String newStatus) { Map<String, List<String>> allowedTransitions = Map.of( "PENDING", List.of("PAID", "CANCELLED"), "PAID", List.of("SHIPPED", "CANCELLED"), "SHIPPED", List.of("COMPLETED"), "COMPLETED", List.of(), "CANCELLED", List.of() ); List<String> allowedNextStatuses = allowedTransitions.get(currentStatus); if (allowedNextStatuses == null || !allowedNextStatuses.contains(newStatus)) { throw new IllegalArgumentException("无效的状态转换: " + currentStatus + " -> " + newStatus); } } // 取消订单 public Order cancelOrder(Long orderId) { Order order = getOrderById(orderId); if (!"PENDING".equals(order.getStatus()) && !"PAID".equals(order.getStatus())) { throw new IllegalArgumentException("只能取消待支付或已支付的订单"); } // 恢复库存 for (OrderItem item : order.getOrderItems()) { productService.increaseStock(item.getProductId(), item.getQuantity()); } order.setStatus("CANCELLED"); order.setUpdateTime(new Date()); return orderRepository.update(order); } // 获取订单统计信息 public OrderStatistics getOrderStatistics() { List<Order> allOrders = orderRepository.findAll(); OrderStatistics stats = new OrderStatistics(); stats.setTotalOrders(allOrders.size()); stats.setTotalRevenue(calculateTotalRevenue(allOrders)); stats.setOrdersByStatus(groupOrdersByStatus(allOrders)); return stats; } // 计算总营收 private BigDecimal calculateTotalRevenue(List<Order> orders) { return orders.stream() .filter(order -> "COMPLETED".equals(order.getStatus())) .map(Order::getTotalAmount) .reduce(BigDecimal.ZERO, BigDecimal::add); } // 按状态分组订单 private Map<String, Long> groupOrdersByStatus(List<Order> orders) { return orders.stream() .collect(Collectors.groupingBy(Order::getStatus, Collectors.counting())); } } // 订单统计类 public class OrderStatistics { private Integer totalOrders; private BigDecimal totalRevenue; private Map<String, Long> ordersByStatus; // Getter和Setter方法 public Integer getTotalOrders() { return totalOrders; } public void setTotalOrders(Integer totalOrders) { this.totalOrders = totalOrders; } public BigDecimal getTotalRevenue() { return totalRevenue; } public void setTotalRevenue(BigDecimal totalRevenue) { this.totalRevenue = totalRevenue; } public Map<String, Long> getOrdersByStatus() { return ordersByStatus; } public void setOrdersByStatus(Map<String, Long> ordersByStatus) { this.ordersByStatus = ordersByStatus; } @Override public String toString() { return String.format("总订单数: %d, 总营收: %.2f, 订单状态分布: %s", totalOrders, totalRevenue, ordersByStatus); } } 控制器层实现 最后,我们实现控制器层来处理HTTP请求: java // 用户控制器 public class UserController { private UserService userService; public UserController(UserService userService) { this.userService = userService; } // 用户注册 public ResponseResult<User> register(UserRegisterRequest request) { try { User user = new User(request.getUsername(), request.getEmail(), request.getPassword()); user.setPhone(request.getPhone()); User registeredUser = userService.register(user); return ResponseResult.success(registeredUser); } catch (IllegalArgumentException e) { return ResponseResult.error(400, e.getMessage()); } catch (Exception e) { return ResponseResult.error(500, "系统错误: " + e.getMessage()); } } // 用户登录 public ResponseResult<User> login(LoginRequest request) { try { User user = userService.login(request.getUsername(), request.getPassword()); return ResponseResult.success(user); } catch (IllegalArgumentException e) { return ResponseResult.error(401, e.getMessage()); } catch (Exception e) { return ResponseResult.error(500, "系统错误: " + e.getMessage()); } } // 更新用户信息 public ResponseResult<User> updateUser(Long userId, UserUpdateRequest request) { try { User user = new User(); user.setId(userId); user.setUsername(request.getUsername()); user.setEmail(request.getEmail()); user.setPhone(request.getPhone()); if (request.getPassword() != null) { user.setPassword(request.getPassword()); } User updatedUser = userService.updateUser(user); return ResponseResult.success(updatedUser); } catch (IllegalArgumentException e) { return ResponseResult.error(400, e.getMessage()); } catch (Exception e) { return ResponseResult.error(500, "系统错误: " + e.getMessage()); } } } // 商品控制器 public class ProductController { private ProductService productService; public ProductController(ProductService productService) { this.productService = productService; } // 添加商品 public ResponseResult<Product> addProduct(ProductCreateRequest request) { try { Product product = new Product( request.getName(), request.getDescription(), request.getPrice(), request.getStock(), request.getCategory() ); Product savedProduct = productService.addProduct(product); return ResponseResult.success(savedProduct); } catch (IllegalArgumentException e) { return ResponseResult.error(400, e.getMessage()); } catch (Exception e) { return ResponseResult.error(500, "系统错误: " + e.getMessage()); } } // 获取商品列表 public ResponseResult<List<Product>> getProducts(String category, String keyword) { try { List<Product> products; if (category != null && !category.isEmpty()) { products = productService.getProductsByCategory(category); } else if (keyword != null && !keyword.isEmpty()) { products = productService.searchProducts(keyword); } else { products = productService.getAllProducts(); } return ResponseResult.success(products); } catch (Exception e) { return ResponseResult.error(500, "系统错误: " + e.getMessage()); } } // 获取商品详情 public ResponseResult<Product> getProductDetail(Long productId) { try { Product product = productService.getProductById(productId); return ResponseResult.success(product); } catch (IllegalArgumentException e) { return ResponseResult.error(404, e.getMessage()); } catch (Exception e) { return ResponseResult.error(500, "系统错误: " + e.getMessage()); } } // 更新商品 public ResponseResult<Product> updateProduct(Long productId, ProductUpdateRequest request) { try { Product product = new Product( request.getName(), request.getDescription(), request.getPrice(), request.getStock(), request.getCategory() ); product.setId(productId); Product updatedProduct = productService.updateProduct(product); return ResponseResult.success(updatedProduct); } catch (IllegalArgumentException e) { return ResponseResult.error(400, e.getMessage()); } catch (Exception e) { return ResponseResult.error(500, "系统错误: " + e.getMessage()); } } } // 订单控制器 public class OrderController { private OrderService orderService; public OrderController(OrderService orderService) { this.orderService = orderService; } // 创建订单 public ResponseResult<Order> createOrder(OrderCreateRequest request) { try { Order order = orderService.createOrder( request.getUserId(), request.getProductQuantities(), request.getShippingAddress() ); return ResponseResult.success(order); } catch (IllegalArgumentException e) { return ResponseResult.error(400, e.getMessage()); } catch (Exception e) { return ResponseResult.error(500, "系统错误: " + e.getMessage()); } } // 获取订单详情 public ResponseResult<Order> getOrderDetail(Long orderId) { try { Order order = orderService.getOrderById(orderId); return ResponseResult.success(order); } catch (IllegalArgumentException e) { return ResponseResult.error(404, e.getMessage()); } catch (Exception e) { return ResponseResult.error(500, "系统错误: " + e.getMessage()); } } // 获取用户订单列表 public ResponseResult<List<Order>> getUserOrders(Long userId) { try { List<Order> orders = orderService.getUserOrders(userId); return ResponseResult.success(orders); } catch (Exception e) { return ResponseResult.error(500, "系统错误: " + e.getMessage()); } } // 更新订单状态 public ResponseResult<Order> updateOrderStatus(Long orderId, OrderStatusUpdateRequest request) { try { Order order = orderService.updateOrderStatus(orderId, request.getStatus()); return ResponseResult.success(order); } catch (IllegalArgumentException e) { return ResponseResult.error(400, e.getMessage()); } catch (Exception e) { return ResponseResult.error(500, "系统错误: " + e.getMessage()); } } // 取消订单 public ResponseResult<Order> cancelOrder(Long orderId) { try { Order order = orderService.cancelOrder(orderId); return ResponseResult.success(order); } catch (IllegalArgumentException e) { return ResponseResult.error(400, e.getMessage()); } catch (Exception e) { return ResponseResult.error(500, "系统错误: " + e.getMessage()); } } // 获取订单统计 public ResponseResult<OrderStatistics> getOrderStatistics() { try { OrderStatistics statistics = orderService.getOrderStatistics(); return ResponseResult.success(statistics); } catch (Exception e) { return ResponseResult.error(500, "系统错误: " + e.getMessage()); } } } // 响应结果封装类 public class ResponseResult<T> { private boolean success; private String message; private T data; private Integer code; // 成功响应 public static <T> ResponseResult<T> success(T data) { ResponseResult<T> result = new ResponseResult<>(); result.setSuccess(true); result.setCode(200); result.setMessage("成功"); result.setData(data); return result; } // 错误响应 public static <T> ResponseResult<T> error(Integer code, String message) { ResponseResult<T> result = new ResponseResult<>(); result.setSuccess(false); result.setCode(code); result.setMessage(message); return result; } // Getter和Setter方法 public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public T getData() { return data; } public void setData(T data) { this.data = data; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } } // 请求参数类 public class UserRegisterRequest { private String username; private String email; private String password; private String phone; // Getter和Setter方法 public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } } public class LoginRequest { private String username; private String password; // Getter和Setter方法 public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } public class OrderCreateRequest { private Long userId; private Map<Long, Integer> productQuantities; private String shippingAddress; // Getter和Setter方法 public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public Map<Long, Integer> getProductQuantities() { return productQuantities; } public void setProductQuantities(Map<Long, Integer> productQuantities) { this.productQuantities = productQuantities; } public String getShippingAddress() { return shippingAddress; } public void setShippingAddress(String shippingAddress) { this.shippingAddress = shippingAddress; } } 系统测试与演示 最后,我们创建一个演示类来测试整个系统: java public class ECommerceSystemDemo { public static void main(String[] args) { // 初始化组件 UserRepository userRepository = new UserRepository(); ProductRepository productRepository = new ProductRepository(); OrderRepository orderRepository = new OrderRepository(); UserService userService = new UserService(userRepository); ProductService productService = new ProductService(productRepository); OrderService orderService = new OrderService(orderRepository, productService, userService); UserController userController = new UserController(userService); ProductController productController = new ProductController(productService); OrderController orderController = new OrderController(orderService); // 演示用户注册和登录 System.out.println("=== 用户注册演示 ==="); UserRegisterRequest registerRequest = new UserRegisterRequest(); registerRequest.setUsername("testuser"); registerRequest.setEmail("test@example.com"); registerRequest.setPassword("password123"); registerRequest.setPhone("13800138000"); ResponseResult<User> registerResult = userController.register(registerRequest); System.out.println("注册结果: " + registerResult.isSuccess()); if (registerResult.isSuccess()) { System.out.println("注册用户: " + registerResult.getData()); } // 演示用户登录 System.out.println("\n=== 用户登录演示 ==="); LoginRequest loginRequest = new LoginRequest(); loginRequest.setUsername("testuser"); loginRequest.setPassword("password123"); ResponseResult<User> loginResult = userController.login(loginRequest); System.out.println("登录结果: " + loginResult.isSuccess()); if (loginResult.isSuccess()) { User loggedInUser = loginResult.getData(); System.out.println("登录用户: " + loggedInUser); // 演示添加商品 System.out.println("\n=== 添加商品演示 ==="); ProductCreateRequest productRequest = new ProductCreateRequest(); productRequest.setName("iPhone 15"); productRequest.setDescription("最新款苹果手机"); productRequest.setPrice(new BigDecimal("5999.00")); productRequest.setStock(100); productRequest.setCategory("电子产品"); ResponseResult<Product> productResult = productController.addProduct(productRequest); if (productResult.isSuccess()) { System.out.println("添加商品成功: " + productResult.getData()); } // 添加更多商品 ProductCreateRequest productRequest2 = new ProductCreateRequest(); productRequest2.setName("MacBook Pro"); productRequest2.setDescription("苹果笔记本电脑"); productRequest2.setPrice(new BigDecimal("12999.00")); productRequest2.setStock(50); productRequest2.setCategory("电子产品"); productController.addProduct(productRequest2); // 演示创建订单 System.out.println("\n=== 创建订单演示 ==="); Map<Long, Integer> productQuantities = new HashMap<>(); productQuantities.put(1L, 2); // 购买2台iPhone 15 productQuantities.put(2L, 1); // 购买1台MacBook Pro OrderCreateRequest orderRequest = new OrderCreateRequest(); orderRequest.setUserId(loggedInUser.getId()); orderRequest.setProductQuantities(productQuantities); orderRequest.setShippingAddress("北京市朝阳区xxx街道"); ResponseResult<Order> orderResult = orderController.createOrder(orderRequest); if (orderResult.isSuccess()) { Order order = orderResult.getData(); System.out.println("创建订单成功: " + order.getOrderNumber()); System.out.println("订单总金额: " + order.getTotalAmount()); System.out.println("订单状态: " + order.getStatus()); } // 演示获取订单列表 System.out.println("\n=== 用户订单列表演示 ==="); ResponseResult<List<Order>> ordersResult = orderController.getUserOrders(loggedInUser.getId()); if (ordersResult.isSuccess()) { List<Order> orders = ordersResult.getData(); System.out.println("用户订单数量: " + orders.size()); for (Order order : orders) { System.out.println("订单: " + order.getOrderNumber() + ", 金额: " + order.getTotalAmount() + ", 状态: " + order.getStatus()); } } // 演示订单统计 System.out.println("\n=== 订单统计演示 ==="); ResponseResult<OrderStatistics> statsResult = orderController.getOrderStatistics(); if (statsResult.isSuccess()) { System.out.println("订单统计: " + statsResult.getData()); } } } } 项目总结与学习要点 通过这个完整的电商订单系统实战项目,我们涵盖了以下核心编程概念和技能: 面向对象编程:使用类、对象、继承、封装等OOP概念 设计模式:Repository模式、Service模式、MVC模式 数据结构和算法:集合框架、流处理、数据转换 异常处理:统一的错误处理机制 模块化设计:清晰的分层架构 业务逻辑:完整的订单处理流程 这个项目不仅帮助你理解理论知识,更重要的是让你掌握如何将这些知识应用到实际项目中。每个模块都经过精心设计,确保代码的可读性、可维护性和可扩展性。 在继续深入学习时,你可以考虑为这个系统添加更多功能,比如: 支付集成 库存预警 订单退款 数据持久化(数据库) 缓存优化 安全性增强 记住,编程能力的提升需要不断的实践和总结。希望这个实战项目能够为你的编程学习之路提供有力的支持!

有疑问加站长微信联系(非本文作者))

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

67 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传