女娲造人
发布时间 2023-10-26 08:52:12作者: 橘子味芬达水
实验2:简单工厂模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解简单工厂模式的动机,掌握该模式的结构;
2、能够利用简单工厂模式解决实际问题。
[实验任务一]:女娲造人
使用简单工厂模式模拟女娲(Nvwa)造人(Person),如果传入参数M,则返回一个Man对象,如果传入参数W,则返回一个Woman对象,如果传入参数R,则返回一个Robot对象。请用程序设计实现上述场景。
实验要求:
1. 画出对应的类图;

2. 提交源代码;
|
//抽象产品类:Person接口 public interface Person { void create(); }
|
|
//具体产品类:Man(男人)类 public class Man implements Person{ public Man() { }
@Override public void create() { System.out.println("造男人"); } }
|
|
//具体产品类:Woman(女人)类 public class Woman implements Person{ public Woman() { }
@Override public void create() { System.out.println("造女人"); } }
|
|
//具体产品类:Robot(机器人)类 public class Robot implements Person{ public Robot() { }
@Override public void create() { System.out.println("造机器人"); } }
|
|
//工厂类:Nvwa(女娲)类 public class Nvwa { public static Person getPerson(String person) throws Exception { if (person.equalsIgnoreCase("M")){ return new Man(); }else if (person.equalsIgnoreCase("W")){ return new Woman(); }else if (person.equalsIgnoreCase("R")){ return new Robot(); }else { throw new Exception("对不起,不能造该类人"); } } }
|
|
import java.util.Scanner;
//测试类 public class Main { public static void main(String[] args) throws Exception { Scanner type = new Scanner(System.in); System.out.print("请输入参数: "); String s = type.nextLine(); Person person = Nvwa.getPerson(s); person.create(); type.close(); } }
|
运行截图:
