使用简单工厂模式模拟女娲(Nvwa)造人(Person),如果传入参数M,则返回一个Man对象,如果传入参数W,则返回一个Woman对象,请实现该场景。现需要增加一个新的Robot类,如果传入参数R,则返回一个Robot对象,对代码进行修改并注意女娲的变化。
模式结构
实例代码
- person.java
public interface person {
public void make();
}
- ConcretePersonM.java
public class ConcretePersonM implements person{
public void make(){
System.out.println("Man!");
}
}
- ConcretePersonW.java
public class ConcretePersonW implements person{
public void make(){
System.out.println("Woman!");
}
}
- ConcretePersonR.java
public class ConcreteRobotR implements person{
public void make() {
System.out.println("Robot!");
}
}
- Nvwa.java
public class Nvwa {
public static person productPerson(String brand) throws Exception{
if(brand.equalsIgnoreCase("M")){
System.out.println("女娲制造了男模型");
return new ConcretePersonM();
}
else if(brand.equalsIgnoreCase("W")){
System.out.println("女娲制造了女模型");
return new ConcretePersonW();
}
else if(brand.equalsIgnoreCase("R")){
System.out.println("女娲制造了机器人");
return new ConcreteRobotR();
}
else{
throw new Exception("女娲目前不生产其他模型");
}
}
}
辅助代码
- XML操作工具类XMLUtilPerson.java
import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.*;
public class XMLUtilPerson {
public static String getBrandName(){
try{
DocumentBuilderFactory dFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=dFactory.newDocumentBuilder();
Document doc;
doc= builder.parse(new File("configPerson.xml"));
NodeList nl=doc.getElementsByTagName("brandName");
Node classNode=nl.item(0).getFirstChild();
String brandName=classNode.getNodeValue().trim();
return brandName;
}catch(Exception e){
e.printStackTrace();
return null;
}
}
}
- 配置文件configPerson.xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
<brandName>R</brandName>
</config>
- 客户端测试类Client.java
public class Client {
public static void main(String args[]){
try{
person p;
String brandName=XMLUtilPerson.getBrandName();
p=Nvwa.productPerson(brandName);
p.make();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
}
结果
-
在配置文件中将< bandName >节点中的内容设置为:M,结果为:
-
在配置文件中将< bandName >节点中的内容设置为:W,结果为:
-
在配置文件中将< bandName >节点中的内容设置为:R,结果为: