[实验任务一]:女娲造人
使用简单工厂模式模拟女娲(Nvwa)造人(Person),如果传入参数M,则返回一个Man对象,如果传入参数W,则返回一个Woman对象,如果传入参数R,则返回一个Robot对象。请用程序设计实现上述场景。
实验要求:
1.画出对应的类图;
2.提交源代码;
3.注意编程规范。
类图:
源代码:
Person
package test; public interface Person { public void make(); } Man
package test; public class Man implements Person{ public Man() { } public void make(){ System.out.print("生产男人"); } } Woman
package test; public class Woman implements Person{ public Woman() { } public void make() { System.out.print("生产女人"); } } Robot
package test; public class Woman implements Person{ public Woman() { } public void make() { System.out.print("生产女人"); } } Nvwa
package test; 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; } } } TEST1
package test; import java.util.Scanner; public class test1 { 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(); } }
标签:Woman,package,每日,System,工厂,Person,test,随笔,public From: https://www.cnblogs.com/jiacheng-712/p/17815781.html