设计模式__简单工厂

本文介绍了一种使用工厂模式和接口实现不同电视品牌实例化的Java编程实践。通过具体示例,展示了如何根据配置文件中的品牌名称动态创建海尔或海信电视对象并调用其播放方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

了解—https://blog.youkuaiyun.com/u013132035/article/details/80633755
https://www.cnblogs.com/toutou/p/4899388.html

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("对不起,暂不能生产该品牌电视机!");
		}
	}
}
public interface TV
{
	public void play();
}
public class HaierTV implements TV
{
	public void play()
	{
		System.out.println("海尔电视机播放中......");
	}
}
public class HisenseTV implements TV
{
	public void play()
	{
		System.out.println("海信电视机播放中......");
	}	
}
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());
         }
	}
}

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;
           	}
		}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值