MST

星途 面试题库

面试题:利用Java接口与抽象类实现复杂业务场景下的设计模式优化

假设你正在开发一个电商系统,商品有不同的类型(实体商品、虚拟商品等),每种商品有不同的计价方式、库存管理方式。请使用Java接口与抽象类,结合合适的设计模式,设计出一个可扩展、易维护的架构,并说明你选择的设计模式以及接口和抽象类在其中的关键设计点。
27.8万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

1. 设计模式选择

策略模式。策略模式定义了一系列算法,将每个算法封装起来,使它们可以相互替换,让算法的变化独立于使用算法的客户。在电商系统中,不同类型商品的计价方式和库存管理方式就如同不同的算法,适合用策略模式来处理。

2. 接口设计

计价方式接口

public interface PricingStrategy {
    double calculatePrice(double basePrice);
}

这个接口定义了计算价格的方法,不同商品类型的计价策略实现此接口。

库存管理方式接口

public interface InventoryManagementStrategy {
    void updateInventory(int quantity);
    int getCurrentInventory();
}

此接口定义了更新库存和获取当前库存的方法,不同商品类型的库存管理策略实现此接口。

3. 抽象类设计

public abstract class Product {
    private String name;
    private double basePrice;
    private PricingStrategy pricingStrategy;
    private InventoryManagementStrategy inventoryManagementStrategy;

    public Product(String name, double basePrice, PricingStrategy pricingStrategy, InventoryManagementStrategy inventoryManagementStrategy) {
        this.name = name;
        this.basePrice = basePrice;
        this.pricingStrategy = pricingStrategy;
        this.inventoryManagementStrategy = inventoryManagementStrategy;
    }

    public double getFinalPrice() {
        return pricingStrategy.calculatePrice(basePrice);
    }

    public void updateProductInventory(int quantity) {
        inventoryManagementStrategy.updateInventory(quantity);
    }

    public int getProductInventory() {
        return inventoryManagementStrategy.getCurrentInventory();
    }

    // 其他通用的商品方法可以在这里定义
}

抽象类 Product 包含商品的通用属性和行为,通过组合的方式关联 PricingStrategyInventoryManagementStrategy 接口,使得不同商品类型可以根据自身需求选择不同的计价和库存管理策略。

4. 具体商品类型实现

实体商品

public class PhysicalProduct extends Product {
    public PhysicalProduct(String name, double basePrice, PricingStrategy pricingStrategy, InventoryManagementStrategy inventoryManagementStrategy) {
        super(name, basePrice, pricingStrategy, inventoryManagementStrategy);
    }
    // 实体商品可能有额外的方法或重写抽象类的方法
}

虚拟商品

public class VirtualProduct extends Product {
    public VirtualProduct(String name, double basePrice, PricingStrategy pricingStrategy, InventoryManagementStrategy inventoryManagementStrategy) {
        super(name, basePrice, pricingStrategy, inventoryManagementStrategy);
    }
    // 虚拟商品可能有额外的方法或重写抽象类的方法
}

5. 关键设计点说明

  • 接口关键设计点:接口定义了行为的契约,使得不同商品类型的计价和库存管理方式可以以一种统一的方式被调用。不同的具体策略类实现这些接口,提供具体的行为实现,这样可以实现行为的可替换性和扩展性。
  • 抽象类关键设计点:抽象类封装了商品的通用属性和行为,通过组合接口的方式,将变化的部分(计价和库存管理策略)外部化,使得具体商品类型只需要关心自身特有的属性和行为,并且可以轻松地切换策略。同时,抽象类也为具体商品类型提供了一个通用的基础,便于代码的复用和维护。

通过这样的设计,当有新的商品类型或新的计价、库存管理方式出现时,只需要实现相应的接口并在具体商品类型中使用,无需修改大量现有代码,符合可扩展、易维护的要求。