实验2:简单工厂模式
软件设计 石家庄铁道大学信息学院
实验2:简单工厂模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解简单工厂模式的动机,掌握该模式的结构;
2、能够利用简单工厂模式解决实际问题。
[实验任务一]:女娲造人
使用简单工厂模式模拟女娲(Nvwa)造人(Person),如果传入参数M,则返回一个Man对象,如果传入参数W,则返回一个Woman对象,如果传入参数R,则返回一个Robot对象。请用程序设计实现上述场景。
实验要求:
1. 对应的类图;

2. 提交源代码;
(1) 抽象产品角色Person
package com.hua; public interface Person { public void create(); }
(2) 具体产品角色Man,Woman,Robot
package com.hua; public class Man implements Person { public void create() { System.out.println("制造了男性"); } } package com.hua; public class Woman implements Person{ public void create() { System.out.println("制造了女性"); } } package com.hua; public class Robot implements Person{ public void create() { System.out.println("制造了机器人"); } }
(3) 工厂角色Factory
package com.hua;
public class NuWa {
public static Person PersonFactory(String arg)
Person nvwa=null;
if(arg.equalsIgnoreCase("M")) {
nvwa=new Man();
System.out.println("女娲要制造男性了"
}
else if(arg.equalsIgnoreCase("W")) {
nvwa=new Woman();
System.out.println("女娲要制造女性了"
}
else if(arg.equalsIgnoreCase("R")) {
nvwa=new Robot();
System.out.println("女娲要制造机器人了
}
return nvwa;
}
}
主调函数:
package com.hua;
public class main {
public static void main(String[] args) {
Person N,W,R;
N=NuWa.PersonFactory("M");
N.create();
W=NuWa.PersonFactory("W");
W.create();
R=NuWa.PersonFactory("R");
R.create();
}
}
运行截图:


浙公网安备 33010602011771号