使用简单工厂模式模拟女娲(Nvwa)造人(Person),如果传入参数M,则返回一个Man对象,如果传入参数W,则返回一个Woman对象,如果传入参数R,则返回一个Robot对象。请用程序设计实现上述场景。
package SFP; /** * 简单工厂模式 */ //女娲造人工厂 public class NvwaPersonFactory { //抽象类--人类 public abstract class Person{ public void birth(){} } //具体产品类 public class Man extends Person{ @Override public void birth(){ System.out.println("女娲造男人。"); super.birth(); } } public class Woman extends Person{ @Override public void birth(){ System.out.println("女娲造女人。"); super.birth(); } } public class Robot extends Person{ @Override public void birth(){ System.out.println("女娲造机器人。"); super.birth(); } } //造人 public Person getPerson(String type) { Person Person = null; if (type.equalsIgnoreCase("M")) { Person = new Man(); } else if (type.equalsIgnoreCase("W")) { Person = new Woman(); } else if (type.equalsIgnoreCase("R")) { Person = new Robot(); } return Person; } public static void main(String[] args) {//入口 Person person; NvwaPersonFactory nvwaPersonFactory = new NvwaPersonFactory(); person = nvwaPersonFactory.getPerson("M"); person.birth(); person = nvwaPersonFactory.getPerson("W"); person.birth(); person = nvwaPersonFactory.getPerson("R"); person.birth(); } }