软件设计 石家庄铁道大学信息学院
实验4:抽象工厂模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解抽象工厂模式的动机,掌握该模式的结构;
2、能够利用抽象工厂模式解决实际问题。
[实验任务一]:人与肤色
使用抽象工厂模式,完成下述产品等级结构:
实验要求:
1. 画出对应的类图;
2. 提交源代码;
运行截图如下
源代码
package com.sjms; public interface AbstractFactory { public Man produceMan(); public Woman produceWomen(); } package com.sjms; public class BlackHuman implements AbstractFactory{ @Override public Man produceMan() { return new BlackMan(); } @Override public Woman produceWomen() { return new BlackWoman(); } } package com.sjms; public class WriteHuman implements AbstractFactory{ @Override public Man produceMan() { return new WriteMan(); } @Override public Woman produceWomen() { return new WriteWoman(); } } package com.sjms; public class YellowHuman implements AbstractFactory{ @Override public Man produceMan() { return new YellowMan(); } @Override public Woman produceWomen() { return new YellowWoman(); } } package com.sjms; public interface Man { public void play(); } package com.sjms; public interface Woman { public void play(); } package com.sjms; public class BlackMan implements Man{ @Override public void play() { System.out.println("我是黑种男人!"); } } package com.sjms; public class BlackWoman implements Woman{ @Override public void play() { System.out.println("我是黑种女人!"); } } package com.sjms; public class WriteMan implements Man { @Override public void play() { System.out.println("我是白种男人!"); } } package com.sjms; public class WriteWoman implements Woman{ @Override public void play() { System.out.println("我是白种女人!"); } } package com.sjms; public class YellowMan implements Man{ public void play() { System.out.println("我是黄种男人!"); } } package com.sjms; public class YellowWoman implements Woman{ @Override public void play() { System.out.println("我是黄种女人!"); } } package com.sjms.Util; import org.w3c.dom.*; import javax.xml.parsers.*; import java.io.File; //工具类 public class XMLUtil { //生成配置文件中一个名字的实例对象 public static Object getBean(){ try { //创建DOM对象 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //文件解析器--由它读配置文件 DocumentBuilder builder = factory.newDocumentBuilder(); Document doc; //用磁盘绝对路径表示配置文件,写你的config.xml的绝对路径 doc = builder.parse(new File("D:\\JAVA\\CODE\\rjgz\\a1\\t5\\src\\main\\java\\com\\sjms\\Util\\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; } } } package com.sjms; import com.sjms.Util.XMLUtil; public class Client { public static void main(String args[]) { try { AbstractFactory factory; Man m; Woman w; factory=(AbstractFactory) XMLUtil.getBean(); m=factory.produceMan(); m.play(); w=factory.produceWomen(); w.play(); } catch(Exception e) { System.out.println(e.getMessage()); } } }
标签:package,class,sjms,工厂,实验,Override,抽象,com,public From: https://www.cnblogs.com/130-gzh/p/17854814.html