基于MVC模式超市收银台代码
时间: 2024-02-18 16:03:47 浏览: 65
这是一个基于MVC模式的超市收银台代码示例:
Model层:
```python
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
class Cart:
def __init__(self):
self.products = []
def add_product(self, product):
self.products.append(product)
def remove_product(self, product):
self.products.remove(product)
def get_total_price(self):
total = 0
for product in self.products:
total += product.price
return total
```
View层:
```python
class CartView:
def __init__(self, controller):
self.controller = controller
def display_cart(self, cart):
print("当前购物车:")
for product in cart.products:
print(product.name, product.price)
print("总价:", cart.get_total_price())
def get_user_input(self):
return input("请输入商品名称:")
def display_error(self, message):
print("出错了:", message)
```
Controller层:
```python
class CartController:
def __init__(self, cart, view):
self.cart = cart
self.view = view
def run(self):
while True:
self.view.display_cart(self.cart)
user_input = self.view.get_user_input()
if user_input == "exit":
break
product = self.find_product(user_input)
if product:
self.cart.add_product(product)
else:
self.view.display_error("商品不存在!")
def find_product(self, name):
for product in products:
if product.name == name:
return product
return None
```
使用示例:
```python
products = [
Product("苹果", 5),
Product("香蕉", 3),
Product("饮料", 2)
]
cart = Cart()
view = CartView()
controller = CartController(cart, view)
controller.run()
```
这个代码示例中,`Product`类表示一个商品,`Cart`类表示购物车。`CartView`类负责显示购物车的内容,获取用户输入和显示错误信息。`CartController`类负责控制整个购物流程,包括查找商品、添加商品到购物车和展示购物车内容等。整个代码遵循了MVC模式的分层架构,各个层之间的耦合度比较低,易于维护和扩展。
阅读全文