10.22

[实验任务一]:女娲造人

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

 

3.注意编程规范。

posted @     阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
历史上的今天:
2023-10-23 异常处理
点击右上角即可分享
微信分享提示