1.使用命令模式模拟邮局送信
时间: 2023-09-16 21:14:03 浏览: 93
首先,我们需要定义几个角色:
1. 邮局(Invoker):负责发送命令。
2. 邮递员(Command):定义发送信件的接口。
3. 信件(Receiver):实际执行发送信件的操作。
接下来,我们可以先定义一个邮递员的接口:
```java
public interface Command {
void execute();
}
```
然后,我们可以定义一个具体的信件类:
```java
public class Letter {
private String from;
private String to;
private String content;
public Letter(String from, String to, String content) {
this.from = from;
this.to = to;
this.content = content;
}
public void send() {
System.out.println("From: " + from);
System.out.println("To: " + to);
System.out.println("Content: " + content);
System.out.println("The letter has been sent.");
}
}
```
接下来,我们可以定义一个具体的邮递员类:
```java
public class PostmanCommand implements Command {
private Letter letter;
public PostmanCommand(Letter letter) {
this.letter = letter;
}
@Override
public void execute() {
letter.send();
}
}
```
最后,我们可以定义一个邮局类,负责发送信件:
```java
public class PostOffice {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void sendLetter() {
command.execute();
}
}
```
现在,我们可以测试一下:
```java
public static void main(String[] args) {
Letter letter = new Letter("Tom", "Jerry", "Hello Jerry, how are you?");
PostmanCommand command = new PostmanCommand(letter);
PostOffice postOffice = new PostOffice();
postOffice.setCommand(command);
postOffice.sendLetter();
}
```
输出结果:
```
From: Tom
To: Jerry
Content: Hello Jerry, how are you?
The letter has been sent.
```
以上就是使用命令模式模拟邮局送信的完整实现过程。
阅读全文