当前位置: 首页 > article >正文

Java中的设计模式全解及电商应用场景示例

Java中的设计模式全解及电商应用场景示例

设计模式是软件开发中常用的解决方案,提供了可复用的代码结构和设计原则。本文将详细介绍Java中的23种设计模式,并结合电商实际应用场景进行示例说明。


1. 创建型模式

1.1 单例模式(Singleton Pattern)

意图:确保一个类只有一个实例,并提供一个全局访问点。

电商场景:购物车的全局管理对象。

public class ShoppingCart {
    private static ShoppingCart instance;
    
    private ShoppingCart() {}

    public static synchronized ShoppingCart getInstance() {
        if (instance == null) {
            instance = new ShoppingCart();
        }
        return instance;
    }
}

1.2 工厂方法模式(Factory Method Pattern)

意图:定义一个接口,让子类决定实例化哪一个类。

电商场景:根据支付方式生成对应的支付对象。

public interface Payment {
    void pay(double amount);
}

public class CreditCardPayment implements Payment {
    public void pay(double amount) {
        System.out.println("Paid $" + amount + " via Credit Card.");
    }
}

public class PayPalPayment implements Payment {
    public void pay(double amount) {
        System.out.println("Paid $" + amount + " via PayPal.");
    }
}

public class PaymentFactory {
    public static Payment getPayment(String type) {
        return switch (type) {
            case "credit" -> new CreditCardPayment();
            case "paypal" -> new PayPalPayment();
            default -> throw new IllegalArgumentException("Invalid payment type");
        };
    }
}

1.3 抽象工厂模式(Abstract Factory Pattern)

意图:提供一个创建一系列相关或相互依赖对象的接口。

电商场景:根据用户地区生成不同风格的UI组件。

public interface Button {
    void render();
}

public interface TextField {
    void render();
}

public interface UIFactory {
    Button createButton();
    TextField createTextField();
}

public class USUIFactory implements UIFactory {
    public Button createButton() {
        return new USButton();
    }
    public TextField createTextField() {
        return new USTextField();
    }
}

public class EUUIFactory implements UIFactory {
    public Button createButton() {
        return new EUButton();
    }
    public TextField createTextField() {
        return new EUTextField();
    }
}

1.4 建造者模式(Builder Pattern)

意图:将一个复杂对象的构建与表示分离,使得同样的构建过程可以创建不同的表示。

电商场景:生成复杂的订单对象。

public class Order {
    private String orderId;
    private List<String> items;
    private double totalPrice;

    private Order(OrderBuilder builder) {
        this.orderId = builder.orderId;
        this.items = builder.items;
        this.totalPrice = builder.totalPrice;
    }

    public static class OrderBuilder {
        private String orderId;
        private List<String> items = new ArrayList<>();
        private double totalPrice;

        public OrderBuilder(String orderId) {
            this.orderId = orderId;
        }

        public OrderBuilder addItem(String item, double price) {
            items.add(item);
            totalPrice += price;
            return this;
        }

        public Order build() {
            return new Order(this);
        }
    }
}

1.5 原型模式(Prototype Pattern)

意图:通过复制现有实例来创建对象,而不是通过实例化类。

电商场景:批量创建类似商品。

public class Product implements Cloneable {
    private String name;
    private double price;

    public Product(String name, double price) {
        this.name = name;
        this.price = price;
    }

    @Override
    protected Product clone() {
        try {
            return (Product) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new RuntimeException(e);
        }
    }
}

2. 结构型模式

2.1 适配器模式(Adapter Pattern)

意图:将一个类的接口转换为客户端期望的另一种接口。

电商场景:适配不同快递公司的API。

public interface ShippingProvider {
    void ship(String orderId);
}

public class UPSShipping {
    public void sendPackage(String orderId) {
        System.out.println("Shipping via UPS: " + orderId);
    }
}

public class UPSAdapter implements ShippingProvider {
    private UPSShipping upsShipping = new UPSShipping();

    public void ship(String orderId) {
        upsShipping.sendPackage(orderId);
    }
}

2.2 桥接模式(Bridge Pattern)

意图:将抽象部分与其实现部分分离,使它们可以独立变化。

电商场景:实现不同的优惠券类型与折扣策略。

public interface Discount {
    double applyDiscount(double price);
}

public class PercentageDiscount implements Discount {
    private double percentage;

    public PercentageDiscount(double percentage) {
        this.percentage = percentage;
    }

    public double applyDiscount(double price) {
        return price * (1 - percentage / 100);
    }
}

public abstract class Coupon {
    protected Discount discount;

    public Coupon(Discount discount) {
        this.discount = discount;
    }

    public abstract double calculatePrice(double price);
}

public class SeasonalCoupon extends Coupon {
    public SeasonalCoupon(Discount discount) {
        super(discount);
    }

    public double calculatePrice(double price) {
        return discount.applyDiscount(price);
    }
}

2.3 装饰器模式(Decorator Pattern)

意图:动态地给对象添加职责。

电商场景:添加商品额外包装服务。

public interface Product {
    String getDescription();
    double getCost();
}

public class BasicProduct implements Product {
    public String getDescription() {
        return "Basic Product";
    }

    public double getCost() {
        return 10.0;
    }
}

public class GiftWrapDecorator implements Product {
    private Product product;

    public GiftWrapDecorator(Product product) {
        this.product = product;
    }

    public String getDescription() {
        return product.getDescription() + ", Gift Wrapped";
    }

    public double getCost() {
        return product.getCost() + 5.0;
    }
}

2.4 代理模式(Proxy Pattern)

意图:为其他对象提供代理以控制访问。

电商场景:控制访问用户订单信息。

public interface OrderService {
    String getOrderDetails(String orderId);
}

public class RealOrderService implements OrderService {
    public String getOrderDetails(String orderId) {
        return "Order details for: " + orderId;
    }
}

public class OrderServiceProxy implements OrderService {
    private RealOrderService realService = new RealOrderService();

    public String getOrderDetails(String orderId) {
        if (checkAccess()) {
            return realService.getOrderDetails(orderId);
        }
        return "Access Denied!";
    }

    private boolean checkAccess() {
        // Mock access check logic
        return true;
    }
}

2.6 外观模式(Facade Pattern)

意图:为子系统中的一组接口提供一个统一的高层接口,从而简化系统的使用。

电商场景:在下单时,订单系统需要与多个子系统(库存、支付、物流)进行交互。通过外观模式,将这些复杂的调用封装到一个统一的接口中。

public class InventoryService {
    public boolean checkStock(String productId, int quantity) {
        System.out.println("Checking stock for product: " + productId);
        return true;
    }
}

public class PaymentService {
    public boolean processPayment(String userId, double amount) {
        System.out.println("Processing payment for user: " + userId);
        return true;
    }
}

public class ShippingService {
    public void shipOrder(String orderId) {
        System.out.println("Order " + orderId + " is being shipped.");
    }
}

public class OrderFacade {
    private InventoryService inventoryService = new InventoryService();
    private PaymentService paymentService = new PaymentService();
    private ShippingService shippingService = new ShippingService();

    public void placeOrder(String userId, String productId, int quantity, double amount) {
        if (inventoryService.checkStock(productId, quantity) &&
            paymentService.processPayment(userId, amount)) {
            System.out.println("Order placed successfully!");
            shippingService.shipOrder("Order123");
        } else {
            System.out.println("Order placement failed.");
        }
    }
}

2.7 组合模式(Composite Pattern)

意图:将对象组合成树形结构以表示“部分-整体”的层次结构,使客户端可以统一对待单个对象和组合对象。

电商场景:电商平台上的商品分类结构(如“电子产品”下包含“手机”和“笔记本”)。

public interface Category {
    void display();
}

public class ProductCategory implements Category {
    private String name;

    public ProductCategory(String name) {
        this.name = name;
    }

    @Override
    public void display() {
        System.out.println(name);
    }
}

public class CompositeCategory implements Category {
    private String name;
    private List<Category> subCategories = new ArrayList<>();

    public CompositeCategory(String name) {
        this.name = name;
    }

    public void addCategory(Category category) {
        subCategories.add(category);
    }

    @Override
    public void display() {
        System.out.println(name);
        for (Category subCategory : subCategories) {
            subCategory.display();
        }
    }
}

使用示例

CompositeCategory electronics = new CompositeCategory("Electronics");
electronics.addCategory(new ProductCategory("Phones"));
electronics.addCategory(new ProductCategory("Laptops"));

CompositeCategory homeAppliances = new CompositeCategory("Home Appliances");
homeAppliances.addCategory(new ProductCategory("Refrigerators"));
homeAppliances.addCategory(new ProductCategory("Washing Machines"));

CompositeCategory rootCategory = new CompositeCategory("All Categories");
rootCategory.addCategory(electronics);
rootCategory.addCategory(homeAppliances);

rootCategory.display();

2.8 享元模式(Flyweight Pattern)

意图:通过共享相同的对象,减少内存使用并提高性能。

电商场景:商品详情页面中,显示的商品图片可能重复出现。通过享元模式,共享相同的图片对象。

import java.util.HashMap;
import java.util.Map;

public class ProductImage {
    private String imageUrl;

    public ProductImage(String imageUrl) {
        this.imageUrl = imageUrl;
    }

    public void display(String productId) {
        System.out.println("Displaying " + imageUrl + " for product: " + productId);
    }
}

public class ProductImageFactory {
    private static Map<String, ProductImage> imageCache = new HashMap<>();

    public static ProductImage getImage(String imageUrl) {
        if (!imageCache.containsKey(imageUrl)) {
            imageCache.put(imageUrl, new ProductImage(imageUrl));
        }
        return imageCache.get(imageUrl);
    }
}

使用示例

ProductImage image1 = ProductImageFactory.getImage("image1.jpg");
image1.display("Product123");

ProductImage image2 = ProductImageFactory.getImage("image1.jpg"); // 复用相同的对象
image2.display("Product456");

2.9 桥接模式(Bridge Pattern)

意图:将抽象部分与实现部分分离,使它们可以独立变化。

电商场景:支持不同平台的支付方式(如:支付宝和微信支付)与支付环境(如:国内支付和国际支付)。

public interface PaymentMethod {
    void makePayment(double amount);
}

public class Alipay implements PaymentMethod {
    @Override
    public void makePayment(double amount) {
        System.out.println("Payment of $" + amount + " made using Alipay.");
    }
}

public class WeChatPay implements PaymentMethod {
    @Override
    public void makePayment(double amount) {
        System.out.println("Payment of $" + amount + " made using WeChat Pay.");
    }
}

public abstract class Payment {
    protected PaymentMethod method;

    public Payment(PaymentMethod method) {
        this.method = method;
    }

    public abstract void pay(double amount);
}

public class DomesticPayment extends Payment {
    public DomesticPayment(PaymentMethod method) {
        super(method);
    }

    @Override
    public void pay(double amount) {
        System.out.print("Domestic ");
        method.makePayment(amount);
    }
}

public class InternationalPayment extends Payment {
    public InternationalPayment(PaymentMethod method) {
        super(method);
    }

    @Override
    public void pay(double amount) {
        System.out.print("International ");
        method.makePayment(amount);
    }
}

使用示例

Payment domesticAlipay = new DomesticPayment(new Alipay());
domesticAlipay.pay(100);

Payment internationalWeChatPay = new InternationalPayment(new WeChatPay());
internationalWeChatPay.pay(200);

2.10 装饰器模式(Decorator Pattern)

意图:动态地给对象添加职责,而无需修改对象本身。

电商场景:在订单中动态添加促销优惠(如满减、包邮)。

public interface Order {
    double calculateTotal();
    String getDescription();
}

public class BasicOrder implements Order {
    @Override
    public double calculateTotal() {
        return 100.0;
    }

    @Override
    public String getDescription() {
        return "Basic Order";
    }
}

public abstract class OrderDecorator implements Order {
    protected Order order;

    public OrderDecorator(Order order) {
        this.order = order;
    }

    @Override
    public double calculateTotal() {
        return order.calculateTotal();
    }

    @Override
    public String getDescription() {
        return order.getDescription();
    }
}

public class DiscountDecorator extends OrderDecorator {
    public DiscountDecorator(Order order) {
        super(order);
    }

    @Override
    public double calculateTotal() {
        return super.calculateTotal() - 10.0; // 满减优惠
    }

    @Override
    public String getDescription() {
        return super.getDescription() + " with Discount";
    }
}

使用示例

Order order = new BasicOrder();
System.out.println(order.getDescription() + ": $" + order.calculateTotal());

Order discountedOrder = new DiscountDecorator(order);
System.out.println(discountedOrder.getDescription() + ": $" + discountedOrder.calculateTotal());

总结

以上补充了外观模式组合模式享元模式桥接模式装饰器模式的详细内容及电商示例代码。结构型模式主要用于处理类和对象的组合关系,通过这些模式,开发者可以设计出更灵活、高效且易维护的代码结构。结合实际业务场景,能够更直观地理解这些模式的意义及作用。


3. 行为型模式

3.1 策略模式(Strategy Pattern)

意图:定义一系列算法,使得它们可以互换。

电商场景:实现不同的商品排序策略。

public interface SortStrategy {
    void sort(List<String> items);
}

public class PriceSortStrategy implements SortStrategy {
    public void sort(List<String> items) {
        // Sort by price
    }
}

public class RatingSortStrategy implements SortStrategy {
    public void sort(List<String> items) {
        // Sort by rating
    }
}

3.2 模板方法模式(Template Method Pattern)

意图:定义一个操作的算法骨架,而将某些步骤的实现延迟到子类。

电商场景:处理不同类型订单(普通订单、预售订单)的通用逻辑。

public abstract class OrderProcessor {
    public final void processOrder() {
        validateOrder();
        deductInventory();
        calculatePrice();
        createInvoice();
    }

    protected abstract void validateOrder();

    protected abstract void deductInventory();

    protected abstract void calculatePrice();

    private void createInvoice() {
        System.out.println("Invoice created!");
    }
}

public class RegularOrderProcessor extends OrderProcessor {
    @Override
    protected void validateOrder() {
        System.out.println("Validating regular order...");
    }

    @Override
    protected void deductInventory() {
        System.out.println("Deducting inventory for regular order...");
    }

    @Override
    protected void calculatePrice() {
        System.out.println("Calculating price for regular order...");
    }
}

3.3 观察者模式(Observer Pattern)

意图:定义对象间的一对多依赖关系,当一个对象状态改变时,其依赖者会收到通知。

电商场景:实现商品库存变化的通知功能。

public interface Observer {
    void update(String product, int quantity);
}

public class Customer implements Observer {
    private String name;

    public Customer(String name) {
        this.name = name;
    }

    public void update(String product, int quantity) {
        System.out.println(name + " notified: " + product + " is back in stock with quantity " + quantity);
    }
}

public class ProductStock {
    private List<Observer> observers = new ArrayList<>();
    private String product;
    private int quantity;

    public ProductStock(String product) {
        this.product = product;
    }

    public void addObserver(Observer observer) {
        observers.add(observer);
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
        notifyObservers();
    }

    private void notifyObservers() {
        for (Observer observer : observers) {
            observer.update(product, quantity);
        }
    }
}

3.4 状态模式(State Pattern)

意图:允许对象在其内部状态改变时改变其行为。

电商场景:订单状态管理(如:待支付、已支付、已发货等)。

public interface OrderState {
    void handleOrder();
}

public class PendingState implements OrderState {
    public void handleOrder() {
        System.out.println("Order is pending payment.");
    }
}

public class PaidState implements OrderState {
    public void handleOrder() {
        System.out.println("Order has been paid. Preparing for shipment.");
    }
}

public class ShippedState implements OrderState {
    public void handleOrder() {
        System.out.println("Order has been shipped.");
    }
}

public class Order {
    private OrderState state;

    public void setState(OrderState state) {
        this.state = state;
    }

    public void processOrder() {
        state.handleOrder();
    }
}

3.5 命令模式(Command Pattern)

意图:将请求封装为对象,从而可以用不同的请求对客户端进行参数化。

电商场景:实现商品的批量操作(如:上下架、删除)。

public interface Command {
    void execute();
}

public class AddProductCommand implements Command {
    private Product product;

    public AddProductCommand(Product product) {
        this.product = product;
    }

    public void execute() {
        System.out.println("Adding product: " + product.getName());
    }
}

public class RemoveProductCommand implements Command {
    private Product product;

    public RemoveProductCommand(Product product) {
        this.product = product;
    }

    public void execute() {
        System.out.println("Removing product: " + product.getName());
    }
}

public class CommandInvoker {
    private List<Command> commands = new ArrayList<>();

    public void addCommand(Command command) {
        commands.add(command);
    }

    public void executeCommands() {
        for (Command command : commands) {
            command.execute();
        }
        commands.clear();
    }
}

3.6 责任链模式(Chain of Responsibility Pattern)

意图:将请求沿着处理者链传递,直到有一个处理者处理它。

电商场景:实现订单的审核流程(如:库存检查、支付检查)。

public abstract class OrderHandler {
    protected OrderHandler nextHandler;

    public void setNextHandler(OrderHandler nextHandler) {
        this.nextHandler = nextHandler;
    }

    public abstract void handleOrder(Order order);
}

public class InventoryCheckHandler extends OrderHandler {
    public void handleOrder(Order order) {
        if (order.hasSufficientInventory()) {
            System.out.println("Inventory check passed.");
            if (nextHandler != null) {
                nextHandler.handleOrder(order);
            }
        } else {
            System.out.println("Inventory check failed.");
        }
    }
}

public class PaymentCheckHandler extends OrderHandler {
    public void handleOrder(Order order) {
        if (order.isPaid()) {
            System.out.println("Payment check passed.");
            if (nextHandler != null) {
                nextHandler.handleOrder(order);
            }
        } else {
            System.out.println("Payment check failed.");
        }
    }
}

3.7 迭代器模式(Iterator Pattern)

意图:提供一种方法访问一个聚合对象中的元素,而无需暴露其内部表示。

电商场景:实现订单集合的迭代。

public interface Iterator<T> {
    boolean hasNext();
    T next();
}

public class OrderCollection implements Iterable<Order> {
    private List<Order> orders = new ArrayList<>();

    public void addOrder(Order order) {
        orders.add(order);
    }

    public Iterator<Order> iterator() {
        return new OrderIterator(orders);
    }

    private class OrderIterator implements Iterator<Order> {
        private int index = 0;

        public boolean hasNext() {
            return index < orders.size();
        }

        public Order next() {
            return orders.get(index++);
        }
    }
}

3.8 备忘录模式(Memento Pattern)

意图:捕获对象的内部状态,并在以后恢复。

电商场景:实现购物车的撤销操作。

public class ShoppingCartMemento {
    private List<String> items;

    public ShoppingCartMemento(List<String> items) {
        this.items = new ArrayList<>(items);
    }

    public List<String> getItems() {
        return items;
    }
}

public class ShoppingCart {
    private List<String> items = new ArrayList<>();

    public void addItem(String item) {
        items.add(item);
    }

    public ShoppingCartMemento save() {
        return new ShoppingCartMemento(items);
    }

    public void restore(ShoppingCartMemento memento) {
        items = memento.getItems();
    }
}

总结

通过本文,我们详细讲解了Java中的23种设计模式,并结合电商场景给出了对应的示例代码。这些设计模式不仅能够解决常见开发问题,还能提升代码的复用性、可扩展性和可维护性。希望这些内容能为你的学习和实际开发带来帮助!


http://www.kler.cn/a/441708.html

相关文章:

  • NextJs - ServerAction获取文件并处理Excel
  • Linux TCP 之 RTT 采集与 RTO 计算
  • 可以自己部署的微博 Mastodon
  • C语言之图像文件的属性
  • HTML语言的数据库编程
  • Visual Studio Community 2022(VS2022)安装方法
  • IP数据云查询IP归属地信息
  • 数据结构:Win32 API详解
  • CXF WebService SpringBoot 添加拦截器,处理响应报文格式
  • React里循环tab列表,并实现点击切换class
  • C语言学习day19:结构体/枚举/共用体/游戏结构体的逆向分析
  • Uniapp安卓端获取手机号码
  • Docker中 localhost 与 0.0.0.0 的区别详解
  • oracle client linux服务器安装教程
  • git SSL certificate problem: unable to get local issuer certificate
  • 只出现一次的数字(字节面试题 最优解)
  • OpenCV 功能函数介绍 (二)
  • awk使用详解
  • 【WPF】RenderTargetBitmap的使用
  • 如何让你的 PHP 应用坚不可摧
  • 【网络安全】掌握 Active Directory 攻防审计实操知识点
  • MaskGCT——开源文本转语音模型,可模仿任何人说话声音
  • 宝塔 搭建HOJ 配置域名 反向代理 开启https访问
  • Android使用PorterDuffXfermode的模式PorterDuff.Mode.SRC_OUT实现橡皮擦,Kotlin(1)
  • Flink-Learning全面探索流式处理的卓越框架
  • 【win10+RAGFlow+Ollama】搭建本地大模型助手(教程+源码)