实验二:简单工厂模式
// 抽象类 Person
abstract class Person {
abstract void eat();
abstract void sleep();
}
// 男性类 Man
class Man extends Person {
@Override
void eat() {
System.out.println("Man is eating.");
}
@Override
void sleep() {
System.out.println("Man is sleeping.");
}
}
// 女性类 Woman
class Woman extends Person {
@Override
void eat() {
System.out.println("Woman is eating.");
}
@Override
void sleep() {
System.out.println("Woman is sleeping.");
}
}
// 机器人类 Robot
class Robot extends Person {
@Override
void eat() {
System.out.println("Robot is charging.");
}
@Override
void sleep() {
System.out.println("Robot is resting.");
}
}
// 工厂类 Nvwa
class Nvwa {
public Person createPerson(String type) {
if (type == null) {
return null;
}
if (type.equalsIgnoreCase("M")) {
return new Man();
} else if (type.equalsIgnoreCase("W")) {
return new Woman();
} else if (type.equalsIgnoreCase("R")) {
return new Robot();
} else {
return null;
}
}
}
// 主类
public class SimpleFactoryPatternDemo {
public static void main(String[] args) {
Nvwa nvwa = new Nvwa();
Person person = nvwa.createPerson("M");
if (person != null) {
person.eat();
person.sleep();
}
person = nvwa.createPerson("W");
if (person != null) {
person.eat();
person.sleep();
}
person = nvwa.createPerson("R");
if (person != null) {
person.eat();
person.sleep();
}
}
}