|
|
|
|
'''
|
|
|
|
|
命令模式(Command Pattern)是一种行为设计模式,它封装了一个请求作为一个对象,从而让你使用不同的请求把客户端与服务端操作解耦。在书城的业务背景中,命令模式可以用来实现例如添加购物车项、结算订单、发送通知等操作。
|
|
|
|
|
|
|
|
|
|
下面是一个简单的使用Python实现的命令模式示例,以书城的购物车操作为例
|
|
|
|
|
'''
|
|
|
|
|
|
|
|
|
|
# 购物车类
|
|
|
|
|
class ShoppingCart:
|
|
|
|
|
def __init__(self):
|
|
|
|
|
self.items = []
|
|
|
|
|
|
|
|
|
|
def add_item(self, book_id, quantity):
|
|
|
|
|
self.items.append({'book_id': book_id, 'quantity': quantity})
|
|
|
|
|
print(f"Added {quantity} of book ID {book_id} to the cart.")
|
|
|
|
|
|
|
|
|
|
def remove_item(self, book_id):
|
|
|
|
|
self.items = [item for item in self.items if item['book_id'] != book_id]
|
|
|
|
|
print(f"Removed book ID {book_id} from the cart.")
|
|
|
|
|
|
|
|
|
|
# 命令接口
|
|
|
|
|
class Command:
|
|
|
|
|
def execute(self):
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
# 具体命令类 - 添加购物车项
|
|
|
|
|
class AddToCartCommand(Command):
|
|
|
|
|
def __init__(self, shopping_cart, book_id, quantity):
|
|
|
|
|
self.shopping_cart = shopping_cart
|
|
|
|
|
self.book_id = book_id
|
|
|
|
|
self.quantity = quantity
|
|
|
|
|
|
|
|
|
|
def execute(self):
|
|
|
|
|
self.shopping_cart.add_item(self.book_id, self.quantity)
|
|
|
|
|
|
|
|
|
|
# 具体命令类 - 移除购物车项
|
|
|
|
|
class RemoveFromCartCommand(Command):
|
|
|
|
|
def __init__(self, shopping_cart, book_id):
|
|
|
|
|
self.shopping_cart = shopping_cart
|
|
|
|
|
self.book_id = book_id
|
|
|
|
|
|
|
|
|
|
def execute(self):
|
|
|
|
|
self.shopping_cart.remove_item(self.book_id)
|
|
|
|
|
|
|
|
|
|
# 调用者(Invoker)类
|
|
|
|
|
class Invoker:
|
|
|
|
|
def __init__(self):
|
|
|
|
|
self.commands = []
|
|
|
|
|
|
|
|
|
|
def store_and_execute_command(self, command):
|
|
|
|
|
self.commands.append(command)
|
|
|
|
|
command.execute()
|
|
|
|
|
|
|
|
|
|
# 客户端代码
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
cart = ShoppingCart()
|
|
|
|
|
invoker = Invoker()
|
|
|
|
|
|
|
|
|
|
# 创建添加购物车项命令
|
|
|
|
|
add_command = AddToCartCommand(cart, "12345", 2)
|
|
|
|
|
invoker.store_and_execute_command(add_command)
|
|
|
|
|
|
|
|
|
|
# 创建移除购物车项命令
|
|
|
|
|
remove_command = RemoveFromCartCommand(cart, "12345")
|
|
|
|
|
invoker.store_and_execute_command(remove_command)
|
|
|
|
|
|
|
|
|
|
'''
|
|
|
|
|
在这个例子中,我们有一个ShoppingCart类,它有两个方法:add_item和remove_item,用于添加和移除购物车项。然后,我们定义了一个命令接口Command和一个调用者Invoker。Invoker可以存储并执行命令。
|
|
|
|
|
|
|
|
|
|
具体命令类AddToCartCommand和RemoveFromCartCommand实现了Command接口,并在execute方法中调用了ShoppingCart的相应操作。
|
|
|
|
|
|
|
|
|
|
客户端代码创建了ShoppingCart实例和Invoker实例,并创建了添加和移除购物车项的具体命令对象。这些命令对象通过调用者的store_and_execute_command方法被存储和执行。
|
|
|
|
|
|
|
|
|
|
这个命令模式的实现将购物车操作和实际的执行逻辑解耦,允许客户端在不知道具体操作的情况下存储和执行命令。这对于支持撤销操作、记录命令历史、排队命令等高级功能非常有用。
|
|
|
|
|
|
|
|
|
|
'''
|