实验4:抽象工厂模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解抽象工厂模式的动机,掌握该模式的结构;
2、能够利用抽象工厂模式解决实际问题。
[实验任务]:人与肤色
使用抽象工厂模式,完成下述产品等级结构:
类图
运行效果
源代码
public class BlackFactory implements PeopleFactory
{
@Override
public Man produceMan()
{
return new BlackMan();
}
@Override
public Woman produceWoman()
{
return new BlackWoman();
}
}
public class BlackMan implements Man
{
@Override
public void show()
{
System.out.println("一个黑种男人");
}
}
public class BlackWoman implements Woman
{
@Override
public void show()
{
System.out.println("一个黑种女人");
}
}
public class Client
{
public static void main(String[] args)
{
try
{
PeopleFactory factory;
Man man;
Woman woman;
//根据xml配置文件动态实例对象
factory = (PeopleFactory) XMLUtil.getBean();
man = factory.produceMan();
man.show();
woman = factory.produceWoman();
woman.show();
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
public interface Man
{
void show();
}
public interface PeopleFactory
{
Man produceMan();
Woman produceWoman();
}
public class WhiteFactory implements PeopleFactory
{
@Override
public Man produceMan()
{
return new WhiteMan();
}
@Override
public Woman produceWoman()
{
return new WhiteWoman();
}
}
public class WhiteMan implements Man
{
@Override
public void show()
{
System.out.println("一个白种男人");
}
}
public class WhiteWoman implements Woman
{
@Override
public void show()
{
System.out.println("一个白种女人");
}
}
public interface Woman
{
void show();
}
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
public class XMLUtil
{
public static Object getBean()
{
try
{
//创建DOM文档对象
DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dFactory.newDocumentBuilder();
Document doc = builder.parse(new File("src/main/resources/config4.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 PeopleFactory
{
@Override
public Man produceMan()
{
return new YellowMan();
}
@Override
public Woman produceWoman()
{
return new YellowWoman();
}
}
public class YellowMan implements Man
{
@Override
public void show()
{
System.out.println("一个黄种男人");
}
}
public class YellowWoman implements Woman
{
@Override
public void show()
{
System.out.println("一个黄种女人");
}
}
config4.xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
<className>Tutorial_4.YellowFactory</className>
</config>