java使用简单工厂模式模拟女娲(Nvwa)造人(Person),如果向造人的工厂方法传入参数“M”,则返回一个男人(MAN)对象,如果传入参数“W”则返回一个Woman对象,Robot类传入参数“R”返回一个robot对象
时间: 2024-02-04 22:04:29 浏览: 314
好的,下面是使用简单工厂模式模拟女娲造人的代码:
首先,我们需要定义一个Person接口,包含一个实现生命的方法:
```java
public interface Person {
void live();
}
```
然后,我们定义MAN、Woman和Robot三个类,它们实现了Person接口:
```java
public class MAN implements Person {
@Override
public void live() {
System.out.println("I am a man, I can work hard.");
}
}
public class Woman implements Person {
@Override
public void live() {
System.out.println("I am a woman, I can give birth to a baby.");
}
}
public class Robot implements Person {
@Override
public void live() {
System.out.println("I am a robot, I can do things that human can't do.");
}
}
```
接下来,我们定义一个简单工厂类,根据传入的参数来创建相应的对象:
```java
public class PersonFactory {
public static Person createPerson(String type) {
if ("M".equals(type)) {
return new MAN();
} else if ("W".equals(type)) {
return new Woman();
} else if ("R".equals(type)) {
return new Robot();
} else {
throw new IllegalArgumentException("Invalid type: " + type);
}
}
}
```
最后,我们可以在客户端代码中使用工厂来创建相应的对象:
```java
public class Client {
public static void main(String[] args) {
Person man = PersonFactory.createPerson("M");
man.live();
Person woman = PersonFactory.createPerson("W");
woman.live();
Person robot = PersonFactory.createPerson("R");
robot.live();
}
}
```
输出结果为:
```
I am a man, I can work hard.
I am a woman, I can give birth to a baby.
I am a robot, I can do things that human can't do.
```
阅读全文