1.产品接口,电视和空调
public interface Television // 电视接口
{
public void play();
}
public interface AirConditioner // 空调
{
public void changeTemperature();
}
2.电子工厂接口,生产电视和空调
public interface EFactory //E工厂接口
{
public Television produceTelevision(); // 生产电视
public AirConditioner produceAirConditioner(); // 生产空调
}
3.具体工厂
海尔工厂生产海尔电视和海尔空调
public class HaierFactory implements EFactory // 海尔工厂
{
public Television produceTelevision()
{
return new HaierTelevision();
}
public AirConditioner produceAirConditioner()
{
return new HairAirConditioner();
}
}
TCL工厂生产TCL电视和TCL空调
public class TCLFactory implements EFactory // TCL工厂
{
public Television produceTelevision()
{
return new TCLTelevision();
}
public AirConditioner produceAirConditioner()
{
return new TCLAirConditioner();
}
}
4.具体产品,海尔电视,海尔空调
public class HaierTelevision implements Television // 海尔电视
{
public void play()
{
System.out.println("海尔电视机播放中......");
}
}
public class HairAirConditioner implements AirConditioner // 海尔空调
{
public void changeTemperature()
{
System.out.println("海尔空调温度改变中......");
}
}
TCL电视,TCL空调
public class TCLTelevision implements Television // TCL电视
{
public void play()
{
System.out.println("TCL电视机播放中......");
}
}
public class TCLAirConditioner implements AirConditioner // TCL空调
{
public void changeTemperature()
{
System.out.println("TCL空调温度改变中......");
}
}
5.配置与获取配置类
<?xml version="1.0"?>
<config>
<className>TCLFactory</className>
</config>
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("./src/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;
}
}
}
6.客户端调用
public class Client
{
public static void main(String args[])
{
try
{
EFactory factory; // 电子工厂
Television tv; // TV
AirConditioner ac; // 空调
factory=(EFactory)XMLUtil.getBean();
// factory = new HaierFactory();
// factory = new TCLFactory();
tv=factory.produceTelevision(); // 工厂生产电视
tv.play(); // 电视播放
ac=factory.produceAirConditioner(); // 工厂生产空调
ac.changeTemperature(); // 空调调节温度
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
结果:
TCL电视机播放中......
TCL空调温度改变中......
类图关系如下,
本文转自TBHacker博客园博客,原文链接:http://www.cnblogs.com/jiqing9006/p/5914337.html,如需转载请自行联系原作者