简单工厂模式java
[实验任务一]:女娲造人
使用简单工厂模式模拟女娲(Nvwa)造人(Person),如果传入参数M,则返回一个Man对象,如果传入参数W,则返回一个Woman对象,如果传入参数R,则返回一个Robot对象。请用程序设计实现上述场景。
所有文件按照图中顺序
package test2; public class Man implements Person{ public Man() { } public void make(){ System.out.print("生产男人"); } }
package test2; public class Nvwa { public Nvwa() { } public static Person Personjudge(String arg ) { //判断参数,再选择调用哪个类 if(arg.equalsIgnoreCase("M")) { return new Man(); }else if(arg.equalsIgnoreCase("W")) { return new Woman(); }else if(arg.equalsIgnoreCase("R")) { return new Robot(); }else { return null; } } }
package test2; public interface Person { public void make(); }
package test2; public class Robot implements Person{ public Robot() { } public void make(){ System.out.print("生产机器人"); } }
package test2; import java.util.Scanner; public class test { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scan = new Scanner(System.in); System.out.print("请输入参数:"); String s = scan.nextLine(); try{ Person p = Nvwa.Personjudge(s); p.make(); }catch(Exception e){ System.out.println(e.getMessage()); } scan.close(); } }
//run此文件
package test2; public class Woman implements Person { public Woman() { } public void make() { System.out.print("生产女人"); } }