女娲
使用简单工厂模式模拟女娲(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();
}
}