使用命令模式设计一个图形绘制系统
时间: 2023-12-10 14:39:07 浏览: 30
首先,我们需要定义一些图形绘制的基本操作,如画线、画矩形、画圆等。然后,我们可以使用命令模式将这些操作封装成对象,并将它们放入一个命令队列中。每个对象都有一个execute()方法,用于执行相应的操作。
下面是一个简单的图形绘制系统的实现:
1. 定义一个图形绘制接口:
```
public interface Shape {
void draw();
}
```
2. 实现具体的图形绘制类:
```
public class Line implements Shape {
public void draw() {
System.out.println("Draw a line.");
}
}
public class Circle implements Shape {
public void draw() {
System.out.println("Draw a circle.");
}
}
public class Rectangle implements Shape {
public void draw() {
System.out.println("Draw a rectangle.");
}
}
```
3. 实现一个命令接口:
```
public interface Command {
void execute();
}
```
4. 实现具体的命令类:
```
public class DrawCommand implements Command {
private Shape shape;
public DrawCommand(Shape shape) {
this.shape = shape;
}
public void execute() {
shape.draw();
}
}
```
5. 实现一个命令队列:
```
import java.util.ArrayList;
import java.util.List;
public class CommandQueue {
private List<Command> commands = new ArrayList<>();
public void addCommand(Command command) {
commands.add(command);
}
public void executeCommands() {
for (Command command : commands) {
command.execute();
}
}
}
```
6. 测试代码:
```
public class Test {
public static void main(String[] args) {
Shape line = new Line();
Shape circle = new Circle();
Shape rectangle = new Rectangle();
CommandQueue commandQueue = new CommandQueue();
commandQueue.addCommand(new DrawCommand(line));
commandQueue.addCommand(new DrawCommand(circle));
commandQueue.addCommand(new DrawCommand(rectangle));
commandQueue.executeCommands();
}
}
```
输出结果:
```
Draw a line.
Draw a circle.
Draw a rectangle.
```
这个图形绘制系统可以轻松地扩展,添加更多的图形绘制操作,只需要实现相应的图形绘制类和命令类即可。