1.简单工厂模式

简单工厂模式(Simple Factory Pattern):又称为静态工厂方法(Static Factory Method)模式,它属于类创建型模式。在简单工厂模式中,可以根据参数的不同返回不同类的实例。简单工厂模式专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类。
2.实例 某电视机厂专为各知名电视机品牌代工生产各类电视机,当需要海尔牌电视机时只需要在调用该工厂的工厂方法时传入参数“Haier”,需要海信电视机时只需要传入参数“Hisense”,工厂可以根据传入的不同参数返回不同品牌的电视机。现使用简单工厂模式来模拟该电视机工厂的生产过程。
项目结构图如下:


定义TV接口。
package com.simoniu.service;
public interface TV {
void play();
}
海尔电视和海信电视实现类。
//HaierTV.java
package com.simoniu.service.bean;
import com.simoniu.service.TV;
public class HaierTV implements TV {
public void play() {
System.out.println("海尔电视机播放中...");
}
}
//HisenseTV.java
package com.simoniu.service.bean;
import com.simoniu.service.TV;
public class HisenseTV implements TV {
public void play() {
System.out.println("海信电视机播放中...");
}
}
电视工厂类
package com.simoniu.service.factory;
import com.simoniu.service.TV;
import com.simoniu.service.bean.HaierTV;
import com.simoniu.service.bean.HisenseTV;
public class TVFactory {
public static TV productTV(String brand) throws Exception{
if("Haier".equalsIgnoreCase(brand)){
System.out.println("电视机工厂生产海尔电视机!");
return new HaierTV();
}else if("Hisense".equalsIgnoreCase(brand)){
System.out.println("电视机工厂生产海信电视机!");
return new HisenseTV();
}else{
throw new Exception("对不起,暂时不能生产该品牌的电视机!");
}
}
}
XML解析工具类。
package com.simoniu.service.utils;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
public class XMLUtilsTV {
/**
* 该方法用于从XML配置文件中提取品牌名称,并返回该品牌名称
* @return
*/
public static String getBrandName(){
DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance();
try {
DocumentBuilder documentBuilder=documentBuilderFactory.newDocumentBuilder();
Document document=documentBuilder.parse(XMLUtilsTV.class .getClassLoader().getResourceAsStream("configTV.xml"));
String brandName=document.getElementsByTagName("brandName").item(0).getTextContent();
return brandName;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
工厂配置文件。
<?xml version="1.0" encoding="UTF-8"?>
<config>
<!--
Haier
Hisense
TCL
-->
<brandName>Hisense</brandName>
</config>
测试类
package com.simoniu.client;
import com.simoniu.service.TV;
import com.simoniu.service.factory.TVFactory;
import com.simoniu.service.utils.XMLUtilsTV;
public class TestSimpleFactoryDemo01 {
public static void main(String[] args) {
String brandName=XMLUtilsTV.getBrandName();
System.out.println("brandName="+brandName);
try {
TV tv=TVFactory.productTV(brandName);
tv.play();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
运行结果:
brandName=Hisense
电视机工厂生产海信电视机!
海信电视机播放中...