种设计模式网上订餐系统的代码
时间: 2023-07-25 14:05:26 浏览: 96
以下是一个基于MVC设计模式的网上订餐系统的代码示例:
Model(模型):
```python
# models.py
class Menu:
def __init__(self, dishes):
self.dishes = dishes
def get_dishes(self):
return self.dishes
class Order:
def __init__(self, customer_name, dish, quantity):
self.customer_name = customer_name
self.dish = dish
self.quantity = quantity
def get_customer_name(self):
return self.customer_name
def get_dish(self):
return self.dish
def get_quantity(self):
return self.quantity
```
View(视图):
```python
# views.py
class MenuView:
def show_menu(self, menu):
print("Welcome to our restaurant! Here is the menu:")
for dish in menu.get_dishes():
print(f"{dish.name} - {dish.price}")
class OrderView:
def get_order_details(self):
customer_name = input("Please enter your name: ")
dish_name = input("What would you like to order? ")
quantity = int(input("How many would you like? "))
return Order(customer_name, dish_name, quantity)
def show_order_confirmation(self, order):
print(f"Thank you, {order.get_customer_name()}! Your order of {order.get_quantity()} {order.get_dish()} has been placed.")
```
Controller(控制器):
```python
# controllers.py
class MenuController:
def __init__(self, menu, menu_view):
self.menu = menu
self.menu_view = menu_view
def show_menu(self):
self.menu_view.show_menu(self.menu)
class OrderController:
def __init__(self, order_view):
self.order_view = order_view
def take_order(self):
order = self.order_view.get_order_details()
self.order_view.show_order_confirmation(order)
```
Main(主程序):
```python
# main.py
from models import Menu, Order
from views import MenuView, OrderView
from controllers import MenuController, OrderController
# Create the menu
dishes = [
Dish("Pizza", 10.99),
Dish("Burger", 8.99),
Dish("Pasta", 12.99)
]
menu = Menu(dishes)
# Initialize the views and controllers
menu_view = MenuView()
menu_controller = MenuController(menu, menu_view)
order_view = OrderView()
order_controller = OrderController(order_view)
# Show the menu and take the order
menu_controller.show_menu()
order_controller.take_order()
```
在这个示例中,我们使用了MVC设计模式,通过将视图、控制器和模型分离,使代码更加清晰和易于维护。模型表示数据和业务逻辑,视图显示数据并接收用户输入,控制器协调模型和视图之间的交互。
阅读全文