使用简单工厂模式模拟女娲(Nvwa)造人(Person),如果传入参数M,则返回一个Man对象,如果传入参数W,则返回一个Woman对象,如果传入参数R,则返回一个Robot对象。
package create;
import create.People;
import create.PeopleFactory;
import create.XMLUtilPeople;
public class Client {
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
People pe;
String createName=XMLUtilPeople.getCreateName();
pe=PeopleFactory.producePeople(createName);
pe.play();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
package create;
import create.People;
public class Man implements People
{
public void play()
{
System.out.println("Man");
}
}
package create;
public interface People
{
public void play();
}
package create;
import create.Man;
import create.Women;
import create.People;
import create.Robot;
public class PeopleFactory {
public static People producePeople(String create) throws Exception
{
if(create.equalsIgnoreCase("M"))
{
System.out.println("Man");
return new Man();
}
else if(create.equalsIgnoreCase("W"))
{
System.out.println("Women");
return new Women();
}
else if(create.equalsIgnoreCase("R"))
{
System.out.println("Robot");
return new Robot();
}
else
{
throw new Exception("对不起,女娲不在,暂不能生产该类型的人或机器!!");
}
}
}
package create;
public class Robot implements People
{
public void play()
{
System.out.println("Robot");
}
}
package create;
public class Women implements People
{
public void play()
{
System.out.println("Women");
}
}
package create;
import java.io.File;
import javax.xml.parsers.*;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XMLUtilPeople {
//该方法用于从XML配置文件中提取品牌名称,并返回该品牌名称
public static String getCreateName()
{
try
{
//创建文档对象
DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dFactory.newDocumentBuilder();
Document doc;
doc = builder.parse(new File("configPeople.xml"));
//获取包含品牌名称的文本节点
NodeList nl = doc.getElementsByTagName("createName");
Node classNode=nl.item(0).getFirstChild();
String createName=classNode.getNodeValue().trim();
return createName;
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
}
sampleFactory类说明
People抽象产品类,它可以是一个接口,也可以是一个抽象类,其中包含了所有产品具有的业务方法。
具体产品类(Many、Women、Robot)是抽象产品类People接口的子类,是一种具体产品,实现了在People接口中定义的业务方法。
工厂类PeopleFactory,是工厂类,它是整个系统的核心,它提供了静态工厂方法producePeople()工厂方法中包含一个字符串类型的参数,在内部业务逻辑根据参数值的不同实例化不同的具体产品类,返回相应的对象。