命令模式的运用

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

实验四命令模式的运用

一、实验目的:

命令模式将“请求”封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象,命令模式也支持可撤销的操作。在熟悉命令模式相关理论知识的基础上,使用命令模式实现图片处理程序。

二、实验要求:

使用命令模式实现图片处理程序,要求如下:

1.图片处理程序要有3张图片。

2.每张图片至少有3种操作。

3.实现类似遥控器的菜单,动态的选择对图片进行的处理。

4.要有“撤消操作”,撤消操作要可以撤销至最后一步。

1、设计并绘制该程序的类图;

2、依照设计的类图使用Java语言编写代码,并实现该程序;

3、除了核心的模式相关类实现外,提供测试环境,按照难度高低,分别是:

a)控制台程序,Client硬编码初始化模式和测试环境,运行结果文本输出;

b)控制台程序,Client初始化测试环境,并根据用户输入运算,运行结果文本输出;

c)设计并实现用户UI,Client初始化测试环境,并根据用户在UI控件上的输入运算,运

行结果文本输出;

三、实验内容:

类图

代码

package Picture;

public interface Command {

public void execute();

public void undo();

}

package Picture;

public class NoCommand implements Command {

public void execute() { }

public void undo() { }

}

package Picture;

public class Picture {

public static final int enlarge=1; //放大图片;

public static final int rotating=2;//旋转图片;

public static final int ensmall=3;// 缩小图片;

public static final int OFF= 0;//"无操作";

int way;

String location;

public Picture(String location) {

this.location = location;

way=OFF;

}

public void enlarge() {

way = enlarge;

System.out.println(location + " 已放大");

}

public void rotating() {

way= rotating;

System.out.println(location + " 已旋转180°");

}

public void ensmall() {

way = ensmall;

System.out.println(location + " 已缩小");

}

public void OFF() {

way= OFF;

System.out.println(location + " 无操作");

}

public int getWay() {

return way;

}

}

package Picture;

public class PictureenlargeCommand implements Command { Picture p;

int prevWay;

public PictureenlargeCommand(Picture p) {

this.p=p;

}

public void execute() {

prevWay = p.getWay();

p.enlarge();

}

public void undo() {

if (prevWay == p.enlarge) {

p.enlarge();

} else if (prevWay ==p.ensmall) {

p.ensmall();;

} else if (prevWay == p.rotating) {

p.rotating();

} else if (prevWay == p.OFF) {

p.OFF();

}

}

}

package Picture;

public class PictureensmallCommand implements Command {

Picture p;

int prevWay;

public PictureensmallCommand(Picture p) {

this.p=p;

}

public void execute() {

prevWay = p.getWay();

p.ensmall();

}

public void undo() {

if (prevWay == p.enlarge) {

p.enlarge();

} else if (prevWay ==p.ensmall) {

p.ensmall();;

} else if (prevWay == p.rotating) {

p.rotating();

} else if (prevWay == p.OFF) {

p.OFF();

}

}

}

package Picture;

public class PictureroatingCommand implements Command { Picture p;

int prevWay;

public PictureroatingCommand(Picture p) {

this.p=p;

}

public void execute() {

prevWay = p.getWay();

p.rotating();

相关文档
最新文档