9.17

实验任务一]:女娲造人
使用简单工厂模式模拟女娲(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("对不起,不能造该类人");
    }
    }
    }
    //测试类
    public class Test {
    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();
    }
    }

posted @ 2024-09-17 13:55  cor0000  阅读(6)  评论(0)    收藏  举报