设计一个基于MVC设计模式的点餐系统,该系统可以供用户点餐,包含的功能有: (1)显示菜品的相关信息(价格、原材料产地和生产日期等) (2)菜品加入购物车 (3)菜品从购物车删除 (4)清空购物车 (5)计算购物车中菜品的总金额 (6)*支付功能(扩展功能) 代码
时间: 2023-06-27 15:01:10 浏览: 90
基于MVC模式的订餐系统的设计与实现
以下是一个基于MVC设计模式的点餐系统的代码示例:
Model:
```python
class MenuItem:
def __init__(self, name, price, origin, production_date):
self.name = name
self.price = price
self.origin = origin
self.production_date = production_date
class ShoppingCart:
def __init__(self):
self.items = []
def add_item(self, item):
self.items.append(item)
def remove_item(self, item):
self.items.remove(item)
def clear_items(self):
self.items = []
def get_total_price(self):
return sum([item.price for item in self.items])
```
View:
```python
class MenuView:
def display_menu(self, menu_items):
print("Menu:")
for i, item in enumerate(menu_items):
print(f"{i+1}. {item.name} - {item.price} yuan")
class ShoppingCartView:
def display_cart(self, cart):
print("Shopping Cart:")
for item in cart.items:
print(f"{item.name} - {item.price} yuan")
class PaymentView:
def display_payment(self, total_price):
print(f"Total cost: {total_price} yuan")
print("Payment successful.")
```
Controller:
```python
class OrderController:
def __init__(self, menu_items, menu_view, cart_view, payment_view):
self.menu_items = menu_items
self.menu_view = menu_view
self.cart_view = cart_view
self.payment_view = payment_view
self.shopping_cart = ShoppingCart()
def display_menu(self):
self.menu_view.display_menu(self.menu_items)
def add_to_cart(self, item_number):
item = self.menu_items[item_number-1]
self.shopping_cart.add_item(item)
self.cart_view.display_cart(self.shopping_cart)
def remove_from_cart(self, item_number):
item = self.shopping_cart.items[item_number-1]
self.shopping_cart.remove_item(item)
self.cart_view.display_cart(self.shopping_cart)
def clear_cart(self):
self.shopping_cart.clear_items()
self.cart_view.display_cart(self.shopping_cart)
def calculate_price(self):
total_price = self.shopping_cart.get_total_price()
self.payment_view.display_payment(total_price)
```
使用示例:
```python
menu_items = [MenuItem("Hamburger", 20, "USA", "2022-01-01"),
MenuItem("Pizza", 30, "Italy", "2022-01-01"),
MenuItem("Hot Dog", 15, "USA", "2022-01-01")]
menu_view = MenuView()
cart_view = ShoppingCartView()
payment_view = PaymentView()
order_controller = OrderController(menu_items, menu_view, cart_view, payment_view)
order_controller.display_menu()
order_controller.add_to_cart(1)
order_controller.add_to_cart(2)
order_controller.remove_from_cart(1)
order_controller.clear_cart()
order_controller.calculate_price()
```
阅读全文