1.使用命令模式模拟邮局送信
时间: 2023-09-16 09:14:04 浏览: 44
命令模式可以用来模拟邮局送信的场景,以下是一个简单的示例代码:
```python
class Mail:
def __init__(self, receiver, content):
self.receiver = receiver
self.content = content
class MailBox:
def __init__(self):
self.mails = []
def add_mail(self, mail):
self.mails.append(mail)
def remove_mail(self, mail):
self.mails.remove(mail)
class MailCommand:
def __init__(self, mailbox, mail):
self.mailbox = mailbox
self.mail = mail
def execute(self):
self.mailbox.add_mail(self.mail)
def undo(self):
self.mailbox.remove_mail(self.mail)
class Mailman:
def __init__(self, mailbox):
self.commands = []
self.mailbox = mailbox
def deliver_mail(self, receiver, content):
mail = Mail(receiver, content)
command = MailCommand(self.mailbox, mail)
command.execute()
self.commands.append(command)
def undo_delivery(self):
if self.commands:
command = self.commands.pop()
command.undo()
```
以上代码中,`Mail` 表示邮件类,`MailBox` 表示邮箱类,`MailCommand` 表示邮件操作命令类,`Mailman` 表示邮递员类。
邮递员可以使用 `deliver_mail` 方法将邮件送到邮箱中,并将邮件操作命令保存在 `commands` 列表中,以便于后续撤销操作。邮递员可以使用 `undo_delivery` 方法撤销最近一次邮件送信操作。
当邮递员使用 `deliver_mail` 方法时,会创建一个邮件对象,并将其添加到邮箱中。同时,也会创建一个邮件操作命令对象,并执行该命令,将邮件添加到邮箱中。当邮递员使用 `undo_delivery` 方法时,会从 `commands` 列表中取出最近一次邮件操作命令对象,并执行其撤销方法,将邮件从邮箱中移除。