You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何用工厂方法模式实现购物车重复商品合并

How to Implement Duplicate Item Merging with Inheritance & Factory Method Pattern

Hey there! Let's walk through exactly how to build this duplicate item merging feature while following your constraints—no changes to the original CashierModel (Class C), using inheritance and the Factory Method pattern. Here's a step-by-step breakdown:

1. Create the BetterBasket Subclass (Extend Class B)

First, we'll make a subclass of your original Basket class. This is where we'll implement the logic to merge duplicate items instead of adding them as separate entries.

// Assuming your original Basket class looks something like this
public class Basket {
    protected List<Item> items; // Or whatever collection you use to store items

    public void add(Item item) {
        // Original logic: adds a new entry every time
        items.add(item);
    }

    // Other existing methods...
}

// Our improved subclass
public class BetterBasket extends Basket {
    @Override
    public void add(Item item) {
        // Check if an identical item already exists in the basket
        for (Item existingItem : items) {
            // Match by item ID (adjust this to your actual unique identifier)
            if (existingItem.getId().equals(item.getId())) {
                // Merge: update quantity and total price
                existingItem.setQuantity(existingItem.getQuantity() + item.getQuantity());
                existingItem.setTotalPrice(existingItem.getTotalPrice() + item.getTotalPrice());
                return; // Exit early since we found and updated the item
            }
        }
        // If no duplicate found, add as a new entry (reuse original logic)
        super.add(item);
    }
}

Note: Adjust the matching logic (like checking item.getId()) to whatever unique identifier your items use—this is key to correctly identifying duplicates.

2. Create the BetterCashierModel Subclass (Extend Class C)

Next, we'll extend the original CashierModel and override its makeBasket method to return our BetterBasket instance instead of the default Basket. This is the Factory Method pattern in action—we're overriding the method that creates the basket object.

// Original CashierModel class (untouched)
public class CashierModel {
    public Basket makeBasket() {
        // Original logic: returns a standard Basket
        return new Basket();
    }

    // Other existing methods that use the basket...
}

// Our improved subclass
public class BetterCashierModel extends CashierModel {
    @Override
    public Basket makeBasket() {
        // Return our custom BetterBasket instead
        return new BetterBasket();
    }
}

3. Replace Usage of CashierModel with BetterCashierModel

Finally, wherever your application was originally instantiating CashierModel, switch it to use BetterCashierModel. Since BetterCashierModel is a subclass, it will work seamlessly with any existing code that expects a CashierModel—no changes needed there!

// Before (original code)
CashierModel cashier = new CashierModel();

// After (our improved version)
CashierModel cashier = new BetterCashierModel();

Key Notes to Keep in Mind

  • Ensure the original Basket.add() method is not marked as private—it needs to be protected or public so we can override it in BetterBasket.
  • Make sure your Item class has getters/setters for quantity and total price (or whatever fields you need to update during merging).
  • This approach follows the Open/Closed Principle: we're extending existing classes instead of modifying them, which keeps your original codebase intact and reduces the risk of breaking existing features.

内容的提问来源于stack exchange,提问作者LactoseLoz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:37:53