[实验任务一]:女娲造人
使用简单工厂模式模拟女娲(Nvwa)造人(Person),如果传入参数M,则返回一个Man对象,如果传入参数W,则返回一个Woman对象,如果传入参数R,则返回一个Robot对象。请用程序设计实现上述场景。
类图
代码
java
Man.java
package Test02;
public class Man implements Person{
@Override
public void born() {
System.out.println("生产Man");
}
}
Nvwa.java
package Test02;
public class Nvwa {
public static Person produce(String per) throws Exception {
if (per.equals("M")){
return new Man();
}else if(per.equals("W")){
return new Woman();
}else if(per.equals("R")){
return new Robot();
}else{
throw new Exception("对不起不能生产");
}
}
public static void main(String[] args) throws Exception {
Person m = Nvwa.produce("M");
m.born();
}
}
Person.java
package Test02;
public interface Person {
public void born();
}
Robot.java
package Test02;
public class Robot implements Person{
@Override
public void born() {
System.out.println("生产Robot");
}
}
Woman.java
package Test02;
public class Woman implements Person{
@Override
public void born() {
System.out.println("生产Woman");
}
}
标签:Woman,java,born,模式,工厂,Person,简单,Test02,public
From: https://www.cnblogs.com/java-six/p/16947260.html