使用Java命令模式设计一个图形绘制系统,该系统可以绘制矩形、椭圆、三角形等图形,恢复和撤销功能。绘制类图并编程实现。
时间: 2024-06-08 07:05:36 浏览: 204
java制作一个图形编辑系统(课题论文 及 代码)
4星 · 用户满意度95%
以下是使用Java命令模式设计的图形绘制系统的类图:
![Command Pattern Class Diagram](https://i.imgur.com/1v0Ff8x.png)
具体实现如下:
1. 定义命令接口 `Command` ,包含 `execute()` 和 `undo()` 方法。
```java
public interface Command {
void execute();
void undo();
}
```
2. 定义具体命令类 `DrawCommand` ,继承 `Command` 接口,用于执行图形绘制操作,并实现 `execute()` 和 `undo()` 方法。
```java
public class DrawCommand implements Command {
private Shape shape;
private Canvas canvas;
public DrawCommand(Shape shape, Canvas canvas) {
this.shape = shape;
this.canvas = canvas;
}
@Override
public void execute() {
canvas.draw(shape);
}
@Override
public void undo() {
canvas.erase(shape);
}
}
```
3. 定义图形类 `Shape` ,包含绘制和擦除方法。
```java
public abstract class Shape {
public abstract void draw();
public abstract void erase();
}
```
4. 定义具体图形类 `Rectangle` 、 `Ellipse` 和 `Triangle` ,继承 `Shape` 类,实现 `draw()` 和 `erase()` 方法。
```java
public class Rectangle extends Shape {
@Override
public void draw() {
System.out.println("绘制矩形");
}
@Override
public void erase() {
System.out.println("擦除矩形");
}
}
public class Ellipse extends Shape {
@Override
public void draw() {
System.out.println("绘制椭圆");
}
@Override
public void erase() {
System.out.println("擦除椭圆");
}
}
public class Triangle extends Shape {
@Override
public void draw() {
System.out.println("绘制三角形");
}
@Override
public void erase() {
System.out.println("擦除三角形");
}
}
```
5. 定义绘图板类 `Canvas` ,包含绘制和擦除方法。
```java
public class Canvas {
public void draw(Shape shape) {
shape.draw();
}
public void erase(Shape shape) {
shape.erase();
}
}
```
6. 定义命令历史记录类 `CommandHistory` ,用于保存命令历史记录并提供撤销方法。
```java
public class CommandHistory {
private Stack<Command> history = new Stack<>();
public void push(Command c) {
history.push(c);
}
public Command pop() {
return history.pop();
}
public boolean isEmpty() {
return history.isEmpty();
}
}
```
7. 客户端代码演示:
```java
public class Client {
public static void main(String[] args) {
// 创建绘图板和命令历史记录对象
Canvas canvas = new Canvas();
CommandHistory history = new CommandHistory();
// 创建具体图形对象
Shape rectangle = new Rectangle();
Shape ellipse = new Ellipse();
Shape triangle = new Triangle();
// 创建具体命令对象并执行
Command drawRectangle = new DrawCommand(rectangle, canvas);
drawRectangle.execute();
history.push(drawRectangle);
Command drawEllipse = new DrawCommand(ellipse, canvas);
drawEllipse.execute();
history.push(drawEllipse);
Command drawTriangle = new DrawCommand(triangle, canvas);
drawTriangle.execute();
history.push(drawTriangle);
// 撤销上一步操作
Command undoCommand = history.pop();
undoCommand.undo();
// 撤销所有操作
while (!history.isEmpty()) {
Command c = history.pop();
c.undo();
}
}
}
```
阅读全文