软件设计 石家庄铁道大学信息学院
实验4:抽象工厂模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解抽象工厂模式的动机,掌握该模式的结构;
2、能够利用抽象工厂模式解决实际问题。
[实验任务一]:人与肤色
使用抽象工厂模式,完成下述产品等级结构:
实验要求:
1. 画出对应的类图;
![](https://img2023.cnblogs.com/blog/2913877/202312/2913877-20231228114913689-1258592974.png)
2. 提交源代码;
package Abstract_factory;
public class BlackFactory implements MWFactory
{
public Man produceMan()
{
return new BlackSkinMan();
}
public Woman produceWomen()
{
return new BlackSkinWomen();
}
}
package Abstract_factory;
public class BlackSkinMan implements Man
{
public void play()
{
System.out.println("我是黑种男人!");
}
}
package Abstract_factory;
public class BlackSkinWomen implements Woman
{
public void play()
{
System.out.println("我是黑种女人!");
}
}
package Abstract_factory;
public class Client
{
public static void main(String args[])
{
try
{
MWFactory factory;
Man m;
Woman w;
factory=(MWFactory)XMLUtil.getBean();
m=factory.produceMan();
m.play();
w=factory.produceWomen();
w.play();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
//run此文件
package Abstract_factory;
public interface Man
{
public void play();
}
package Abstract_factory;
public interface MWFactory
{
public Man produceMan();
public Woman produceWomen();
}
package Abstract_factory;
public class WhiteFactory implements MWFactory
{
public Man produceMan()
{
return new WhiteSkinMan();
}
public Woman produceWomen()
{
return new WhiteSkinWomen();
}
}
package Abstract_factory;
public class WhiteSkinMan implements Man{
public void play()
{
System.out.println("我是白种男人!");
}
}
package Abstract_factory;
public class WhiteSkinWomen implements Woman{
public void play()
{
System.out.println("我是白种女人!");
}
}
package Abstract_factory;
public interface Woman
{
public void play();
}
package Abstract_factory;
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("Cainiao.iml"));
//获取包含类名的文本节点
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;
}
}
}
package Abstract_factory;
public class YellowFactory {
public Man produceMan()
{
return new YellowSkinMan();
}
public Woman produceWomen()
{
return new YellowSkinWomen();
}
}
package Abstract_factory;
public class YellowSkinMan implements Man{
public void play()
{
System.out.println("我是黄种男人!");
}
}
package Abstract_factory;
public class YellowSkinWomen implements Woman{
public void play()
{
System.out.println("我是黄种女人!");
}
}
3.注意编程规范。