某电视机工厂专为各知名品牌电视代工生产工各类电视,当需要海尔电视机时只需要调用给工厂的工厂方法时传入参数“Haier”

,需要海信电视机时只需要传入参数“Hisense” ,工厂可以根据传入的不同参数返回不同品牌电视机。现使用简单工厂模式来模拟该电视工厂的生产过程。

 

 

客户端类:
public class Client
{
	public static void main(String args[])
	{
         try
         {
         	TV tv;
         	String brandName=XMLUtilTV.getBrandName();
         	tv=TVFactory.produceTV(brandName);
         	tv.play();
         }
         catch(Exception e)
         {
         	System.out.println(e.getMessage());
         }
	}
}

 

 

HaierTV类:

public class HaierTV implements TV
{
	public void play()
	{
		System.out.println("海尔电视机播放中......");
	}
}

 

HisenseTV 类:
public class HisenseTV implements TV
{
	public void play()
	{
		System.out.println("海信电视机播放中......");
	}	
}

 

TV接口:

public interface TV
{
	public void play();
}

 

TVFactory类:

public class TVFactory
{
	public static TV produceTV(String brand) throws Exception
	{
		if(brand.equalsIgnoreCase("Haier"))
		{
			System.out.println("电视机工厂生产海尔电视机!");
			return new HaierTV();
		}
		else if(brand.equalsIgnoreCase("Hisense"))
		{
			System.out.println("电视机工厂生产海信电视机!");
			return new HisenseTV();
		}
		else
		{
			throw new Exception("对不起,暂不能生产该品牌电视机!");
		}
	}
}

 

XMLUtilTV类:

import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import java.io.*;
public class XMLUtilTV
{
    //该方法用于从XML配置文件中提取品牌名称,并返回该品牌名称
	public static String getBrandName()
	{
		try
		{
			//创建文档对象
			DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = dFactory.newDocumentBuilder();
			Document doc;							
			doc = builder.parse(new File("configTV.xml")); 
		
			//获取包含品牌名称的文本节点
			NodeList nl = doc.getElementsByTagName("brandName");
            Node classNode=nl.item(0).getFirstChild();
            String brandName=classNode.getNodeValue().trim();
            return brandName;
           }   
           	catch(Exception e)
           	{
           		e.printStackTrace();
           		return null;
           	}
		}
}

 

配置文件:
<?xml version="1.0"?>
<config>
	<brandName>Haier</brandName>
</config>

 

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐