赞
踩
实例一:电视机工厂 将原有的工厂进行分割,为每种品牌的电视机提供一个子工厂,海尔工厂专门负责生产海尔电视机,海信工厂专门负责生产海信电视机,如果需要生产TCL电视机或创维电视机,只需要对应增加一个新的TCL工厂或创维工厂即可,原有的工厂无须做任何修改,使得整个系统具有更加的灵活性和可扩展性。
- Client类:
- public class Client
- {
- public static void main(String args[])
- {
- try
- {
- TV tv;
- TVFactory factory;
- factory=(TVFactory)XMLUtil.getBean();
- tv=factory.produceTV();
- tv.play();
- }
- catch(Exception e)
- {
- System.out.println(e.getMessage());
- }
- }
- }
- config.xml文件
-
- <?xml version="1.0"?>
- <config>
- <className>HisenseTVFactory</className>
- </config>
- HaierTV 类:
-
- public class HaierTV implements TV
- {
- public void play()
- {
- System.out.println("海尔电视机播放中......");
- }
- }
- HaierTVFactory 类:
-
- public class HaierTVFactory implements TVFactory
- {
- public TV produceTV()
- {
- System.out.println("海尔电视机工厂生产海尔电视机。");
- return new HaierTV();
- }
- }
- HisenseTV 类:
-
- public class HisenseTV implements TV
- {
- public void play()
- {
- System.out.println("海信电视机播放中......");
- }
- }
- HisenseTVFactory :
-
- public class HisenseTVFactory implements TVFactory
- {
- public TV produceTV()
- {
- System.out.println("海信电视机工厂生产海信电视机。");
- return new HisenseTV();
- }
- }
- TV类:
-
- public interface TV
- {
- public void play();
- }
- TVFactory类:
- public interface TVFactory
- {
- public TV produceTV();
- }
- XMLUtil类:
-
- 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;
- }
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。