Exercise: Association, Aggregation & Composition
This exercise puts the association, aggregation, and composition lesson into code. You will build an order system where a catalog aggregates products that exist independently, while orders are composed of line items that only exist within a single order.
Scenario
An order system has two top-level objects: a Catalog and a collection of Order instances. The Catalog aggregates Product objects — products exist independently of any order and can be referenced by multiple orders. Each Order is composed of LineItem objects: a line item is created by the order, belongs exclusively to it, and holds a reference to a catalog product plus a quantity. Each command produces exactly one output line.
Commands
| Command | Behavior | Output |
|---|---|---|
["product", sku, price] | Register a product in the catalog | "Catalogued <sku>" |
["additem", order_id, sku, qty] | Add a line item to the order referencing the catalog product. Orders are created on first use. | "Added <qty> <sku> to <order_id>", or "Unknown sku <sku>" if the sku is not in the catalog |
["total", order_id] | Report the sum of price * qty across all line items | "<order_id> total: <sum>" (0 for an order with no items) |
price and qty are integers.
7 product WIDGET 10 product GADGET 25 additem order1 WIDGET 3 additem order1 GADGET 2 additem order2 UNKNOWN 1 total order1 total order2
Catalogued WIDGET Catalogued GADGET Added 3 WIDGET to order1 Added 2 GADGET to order1 Unknown sku UNKNOWN order1 total: 80 order2 total: 0
Your task
Fill in LineItem.subtotal(), Order.add_item(), Order.total(), Catalog.add(), and Catalog.get() so the commands produce the output above.