10.25

wlxdaydayup / 2024-11-13 / 原文

实验2:简单工厂模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解简单工厂模式的动机,掌握该模式的结构;
2、能够利用简单工厂模式解决实际问题。

[实验任务一]:女娲造人
使用简单工厂模式模拟女娲(Nvwa)造人(Person),如果传入参数M,则返回一个Man对象,如果传入参数W,则返回一个Woman对象,如果传入参数R,则返回一个Robot对象。请用程序设计实现上述场景。
实验要求:

  1. 画出对应的类图;

  2. 提交源代码;

  3. package uml;

// Person接口
interface Person {
void speak();
}

// Man类,实现Person接口
class Man implements Person {
@Override
public void speak() {
System.out.println("我是男孩");
}
}

// Woman类,实现Person接口
class Woman implements Person {
@Override
public void speak() {
System.out.println("我是女孩");
}
}

// Robot类,实现Person接口
class Robot implements Person {
@Override
public void speak() {
System.out.println("我是机器人");
}
}

// 女娲类 (简单工厂类)
class Nvwa {
public static Person createPerson(String type) {
switch (type.toUpperCase()) {
case "M":
return new Man();
case "W":
return new Woman();
case "R":
return new Robot();
default:
throw new IllegalArgumentException("无此类型: " + type);
}
}
}

// 测试类
public class Main {
public static void main(String[] args) {
Person man = Nvwa.createPerson("M");
man.speak(); // 输出: I am a Man.

    Person woman = Nvwa.createPerson("W");
    woman.speak();  // 输出: I am a Woman.

    Person robot = Nvwa.createPerson("R");
    robot.speak();  // 输出: I am a Robot.
}

}

3.注意编程规范。