[实验任务一]:女娲造人
使用简单工厂模式模拟女娲(Nvwa)造人(Person),如果传入参数M,则返回一个Man对象,如果传入参数W,则返回一个Woman对象,如果传入参数R,则返回一个Robot对象。请用程序设计实现上述场景。
实验要求:
1.画出对应的类图;
2.提交源代码;
3.注意编程规范。
类图:
2、代码
Main.java
package org.example;
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();
}
}
Man.java
package org.example;
//具体产品类:Man(男人)类
public class Man implements Person{
public Man() {
}
@Override
public void create() {
System.out.println("造男人");
}
}
Nvwa.java
package org.example;
//工厂类: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("对不起,不能造该类人");
}
}
}
person接口
package org.example;
//抽象产品类:Person接口
public interface Person {
void create();
}
Robot.java
package org.example;
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();
}
}
Woman.java
package org.example;
//具体产品类:Woman(女人)类
public class Woman implements Person{
public Woman() {
}
@Override
public void create() {
System.out.println("造女人");
}
}
代码运行:
标签:Woman,java,Person,System,模式,工厂,person,实验,public From: https://www.cnblogs.com/yuanxinglan/p/18498121