实验4:抽象工厂模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解抽象工厂模式的动机,掌握该模式的结构;
2、能够利用抽象工厂模式解决实际问题。
[实验任务一]:人与肤色
使用抽象工厂模式,完成下述产品等级结构:
实验要求:
1. 画出对应的类图;
2. 提交源代码;
- public interface Man {
- public void makeM();
- }
- public class YellowMan implements Man {
- public void makeM() {
- System.out.println("黄男!");
- }
- }
- public class WhiteMan implements Man {
- public void makeM() {
- System.out.println("白男!");
- }
- }
- public class BlackMan implements Man {
- @Override
- public void makeM() {
- System.out.println("黑男!");
- }
- }
- public interface Woman {
- public void makeW();
- }
- public class WhiteWoman implements Woman {
- @Override
- public void makeW() {
- System.out.println("白女!");
- }
- }
- public class BlackWoman implements Woman {
- @Override
- public void makeW() {
- System.out.println("黑女!");
- }
- }
- public class YellowWoman implements Woman {
- public void makeW() {
- System.out.println("黄女!");
- }
- }
- public interface Color {
- public Man produceMan();
- public Woman produceWoman();
- }
- public class Yellow implements Color{
- @Override
- public Man produceMan() {
- return new YellowMan();
- }
- @Override
- public Woman produceWoman() {
- return new YellowWoman();
- }
- }
- public class Black implements Color{
- @Override
- public Man produceMan() {
- return new BlackMan();
- }
- @Override
- public Woman produceWoman() {
- return new BlackWoman();
- }
- }
- package test4;
- /*
- * 读取XML文件并根据存储在XML文件中的类名获取对应的对象
- */
- import javax.xml.parsers.*;
- import org.w3c.dom.*;
- import java.io.File;
- public class XMLUtil {
- @SuppressWarnings("deprecation")
- public static Object getBean() {
- try {
- //创建DOM文档对象
- 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();
- System.out.println("类名: "+ cName); //输出类名
- //通过类名生成实例对象返回
- Class c = Class.forName(cName);
- Object obj = c.newInstance();
- return obj;
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
- }
- public class Client {
- public static void main(String[] args) {
- try
- {
- Color color;
- Man man;
- Woman woman;
- color=(Color)XMLUtil.getBean();
- System.out.println(color);
- woman=color.produceWoman();
- woman.makeW();
- man=color.produceMan();
- man.makeM();
- }catch(Exception e){
- System.out.print(e.getMessage());
- }
- }
- }