使用簡單工廠模式模拟女娲(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());
}
public class Man implements People
{
public void play()
System.out.println("Man");
public interface People
public void play();
import create.Man;
import create.Women;
import create.Robot;
public class PeopleFactory {
public static People producePeople(String create) throws Exception
if(create.equalsIgnoreCase("M"))
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("對不起,女娲不在,暫不能生産該類型的人或機器!!");
public class Robot implements People
public class Women implements People
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()工廠方法中包含一個字元串類型的參數,在内部業務邏輯根據參數值的不同執行個體化不同的具體産品類,傳回相應的對象。