第二次实验:
[实验任务一]:女娲造人
使用简单工厂模式模拟女娲(Nvwa)造人(Person),如果传入参数M,则返回一个Man对象,如果传入参数W,则返回一个Woman对象,如果传入参数R,则返回一个Robot对象。请用程序设计实现上述场景。
类图:
C++实现代码:
#include <iostream> using namespace std; class Person{ public: virtual void eat() = 0; virtual void run() = 0; }; class Man : public Person{ void eat(){ cout<<"男人在吃饭"<<endl; } void run(){ cout<<"男人在跑步"<<endl; } }; class Woman : public Person{ void eat(){ cout<<"女人在吃饭"<<endl; } void run(){ cout<<"女人在跑步"<<endl; } }; class Robot : public Person{ void eat(){ cout<<"机器人在吃饭"<<endl; } void run(){ cout<<"机器人在跑步"<<endl; } }; class Nvwa{ public: Person*getPerson(char people){ if(people == 'M'){ return new Man(); } else if(people == 'W'){ return new Woman(); } else{ return new Robot(); } } }; int main(){ Nvwa *nvwa = new Nvwa(); Person *man = nvwa->getPerson('M'); Person *woman = nvwa->getPerson('W'); Person *robot = nvwa->getPerson('R'); man->eat(); man->run(); woman->eat(); woman->run(); robot->eat(); robot->run(); delete nvwa; nvwa = NULL; delete man; man = NULL; delete woman; woman = NULL; delete robot; robot = NULL; }
Java代码:
男人类:
package SimpleFactoryPattern; public class Gj19Man extends Gj19Person { public void eat() { System.out.println("男人在吃东西!"); } public void run() { System.out.println("男人在跑步!"); } }
女娲类:
package SimpleFactoryPattern; public class Gj19Nvwa extends Gj19Person { public static Gj19Person getPerson(String people) { Gj19Person gj19Person=null; if(people.equalsIgnoreCase("M")) { gj19Person = new Gj19Man(); } else if(people.equalsIgnoreCase("W")) { gj19Person = new Gj19Woman(); } else if(people.equalsIgnoreCase("R")) { gj19Person = new Gj19Robot(); } return gj19Person; } }
女娲造人类:
package SimpleFactoryPattern; import java.util.Scanner; public class Gj19NvwaMakePerson { public static void main(String[] args) { Gj19Person gj19Person; gj19Person = Gj19Nvwa.getPerson("M"); //女娲造男人 gj19Person.eat(); gj19Person = Gj19Nvwa.getPerson("W"); //女娲造女人 gj19Person.eat(); gj19Person = Gj19Nvwa.getPerson("R"); //女娲造机器人 gj19Person.eat(); } }
人类:
package SimpleFactoryPattern; public abstract class Gj19Person { public void eat() { }; public void run() { }; }
机器人类:
package SimpleFactoryPattern; public class Gj19Robot extends Gj19Person { public void eat() { System.out.println("机器人在吃东西!"); } public void run() { System.out.println("机器人在跑步!"); } }
女人类:
package SimpleFactoryPattern; public class Gj19Woman extends Gj19Person { public void eat() { System.out.println("女人在吃东西!"); } public void run() { System.out.println("女人在跑步!"); } }