11.19总结
package test;
public abstract class AbstractCommand {
public abstract int execute(int value);
public abstract int undo();
}
package test;
public class Adder {
private int num=0;
public int add(int value) {
num += value;
return num;
}
}
package test;
public class CalculatorForm {
private AbstractCommand command;
public void setCommand(AbstractCommand command) {
this.command = command;
}
public void compute(int value) {
int i = command.execute(value);
System.out.println("执行结果为" + i);
}
public void undo() {
int i = command.undo();
System.out.println("撤销:" + i);
}
}
package test;
public class Client {
public static void main(String args[]) {
CalculatorForm form = new CalculatorForm();
AbstractCommand command;
command = new ConcreteCommand();
form.setCommand(command);
form.compute(3);
form.compute(4);
form.compute(5);
form.undo();
form.undo();
form.undo();
}
}
package test;
class ConcreteCommand extends AbstractCommand {
private Adder adder = new Adder();
private int value;
public int execute(int value) {
this.value=value;
return adder.add(value);
}
public int undo() {
return adder.add(-value);
}
}
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解简单工厂模式的动机,掌握该模式的结构;
2、能够利用简单工厂模式解决实际问题。
[实验任务一]:女娲造人
使用简单工厂模式模拟女娲(Nvwa)造人(Person),如果传入参数M,则返回一个Man对象,如果传入参数W,则返回一个Woman对象,如果传入参数R,则返回一个Robot对象。请用程序设计实现上述场景。
实验要求:
1.画出对应的类图;
2.提交源代码;
3.注意编程规范。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
Client.java:
package factory;
/**
- 造人测试
- @author Administrator
*/
public class Client {
public static void main(String[] args) {
//生产男人
Person M;
M=Nvwa.factoryMethod("M");
M.make();
//生产女人
Person W;
W=Nvwa.factoryMethod("W");
W.make();
//生产机器人
Person R;
R=Nvwa.factoryMethod("R");
R.make();
}
}
Man.java:
package factory;
public class Man implements Person {
public void make() {
System.out.println("女娲要造男人了");
}
}
Nvwa.java:
package factory;
public class Nvwa {
public static Person factoryMethod(String arg) {
// 判断参数,选择调用哪个类
if (arg.equalsIgnoreCase("M")) {// 男人
return new Man();
} else if (arg.equalsIgnoreCase("W")) {// 女人
return new Woman();
} else if (arg.equalsIgnoreCase("R")) {// 机器人
return new Robot();
} else {
return null;
}
}
}
Person.java:
package factory;
public interface Person {
public void make();
}
Robot.java:
package factory;
public class Robot implements Person{
public void make() {
System.out.println("女娲要造机器人了");
}
}
Woman.java:
package factory;
public class Woman implements Person {
public void make() {
System.out.println("女娲要造女人了");
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏