实验2:简单工厂模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解简单工厂模式的动机,掌握该模式的结构;
2、能够利用简单工厂模式解决实际问题。
[实验任务一]:女娲造人
使用简单工厂模式模拟女娲(Nvwa)造人(Person),如果传入参数M,则返回一个Man对象,如果传入参数W,则返回一个Woman对象,如果传入参数R,则返回一个Robot对象。请用程序设计实现上述场景。
实验要求:
1. 画出对应的类图;
2.提交源代码;
// 人类的抽象类
abstract class
Person {
public abstract void sayHello();
}
// 男人类
class Man
extends Person {
@Override
public void sayHello() {
System.out.println("I'm a
man.");
}
}
// 女人类
class Woman
extends Person {
@Override
public void sayHello() {
System.out.println("I'm a
woman.");
}
}
// 机器人类(这里假设机器人也有类似打招呼的行为)
class Robot {
public void sayHello() {
System.out.println("I'm a
robot.");
}
}
// 简单工厂类
class
NvwaFactory {
public static Object createPerson(String
type) {
if ("M".equals(type)) {
return new Man();
} else if ("W".equals(type))
{
return new Woman();
} else if ("R".equals(type))
{
return new Robot();
}
return null;
}
}
// 测试类
public class
Main {
public static void main(String[] args) {
Person man = (Person)
NvwaFactory.createPerson("M");
if (man!= null) {
man.sayHello();
}
Person woman = (Person)
NvwaFactory.createPerson("W");
if (woman!= null) {
woman.sayHello();
}
Robot robot = (Robot)
NvwaFactory.createPerson("R");
if (robot!= null) {
robot.sayHello();
}
}
}
3.注意编程规范。