使用抽象工厂模式,完成下述产品等级结构:
实现
UML类图
public class BlackFactory implements MWFactory
{
public Man produceMan()
{
return new BlackSkinMan();
}
public Women produceWomen()
{
return new BlackSkinWomen();
}
}
public class BlackSkinMan implements Man
{
public void play()
{
System.out.println("黑色皮肤的男人出现");
}
}
public class BlackSkinWomen implements Women
{
public void play()
{
System.out.println("黑色皮肤的女人出现");
}
}
public class Client
{
public static void main(String args[])
{
try
{
MWFactory factory;
Man m;
Women w;
factory=(MWFactory)XMLUtil.getBean();
m=factory.produceMan();
m.play();
w=factory.produceWomen();
w.play();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
public interface Man
{
public void play();
}
public interface MWFactory
{
public Man produceMan();
public Women produceWomen();
}
public class WhiteFactory implements MWFactory
{
public Man produceMan()
{
return new WhiteSkinMan();
}
public Women produceWomen()
{
return new WhiteSkinWomen();
}
}
public class WhiteSkinMan implements Man
{
public void play()
{
System.out.println("白色皮肤的男人出现");
}
}
public class WhiteSkinWomen implements Women{
public void play()
{
System.out.println("白色皮肤的女人出现");
}
}
public interface Women
{
public void play();
}
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import java.io.*;
public class XMLUtil
{
//该方法用于从XML配置文件中提取具体类类名,并返回一个实例对象
public static Object getBean()
{
try
{
//创建文档对象
DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dFactory.newDocumentBuilder();
Document doc;
doc = builder.parse(new File("config.xml"));
//获取包含类名的文本节点
NodeList nl = doc.getElementsByTagName("className");
Node classNode=nl.item(0).getFirstChild();
String cName=classNode.getNodeValue();
//通过类名生成实例对象并将其返回
Class c=Class.forName(cName);
Object obj=c.newInstance();
return obj;
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
}
public class YellowFactory implements MWFactory
{
public Man produceMan()
{
return new YellowSkinMan();
}
public Women produceWomen()
{
return new YellowSkinWomen();
}
}
public class YellowSkinMan implements Man
{
public void play()
{
System.out.println("黄色皮肤男人出现");
}
}
public class YellowSkinWomen implements Women{
public void play()
{
System.out.println("黄色皮肤的女人出现");
}
}
AbstractFactory 抽象工厂(AbstractFactory)
用于声明生成抽象产品的方法,在抽象工厂里可以定义一组方法,每一个方法对应一个产品等级结构。
ConcreteFactory 具体工厂(BlackFactory、WhiteFactory、YellowlFactory)
实现了抽象工厂声明的抽象产品的方法,生成一组具体产品,这些产品构成了一个产品族,每一个产品都位于某个产品等级结构中。
AbstractProduct 抽象产品(Man、Women)
为每种产品声明接口,定义了产品的抽象业务方法。
ConcreteProduct 具体产品(BM、WM、YM、BW、WW、YW)
定义具体工厂生产的具体产品对象,实现抽象产品接口定义的业务方法。