标签:resources tno 影响 格式 详细 活性 源代码 ica ping
简单工厂模式包含如下角色:
简单电视机工厂:实例说明
简单电视机工厂:参考类图
简单电视机工厂:参考代码
代码结构:
TV接口
package simplefactory; public interface TV { public void play(); }
HaierTV类
package simplefactory; public class HaierTV implements TV { @Override public void play() { System.out.println("海尔电视机播放中···"); } }
HisenseTV类
package simplefactory; public class HisenseTV implements TV { @Override public void play() { System.out.println("海信电视机播放中···"); } }
TVFactory类
package simplefactory; 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类
package simplefactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; public class XMLUtilTV { //该方法用于从XML配置文件中提取品牌名称,并返回该品牌名称 public static String getBrandName() { try { //创建文档对象 DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = dFactory.newDocumentBuilder(); Document doc; doc = builder.parse(new File("D:\\MyNewWorld\\Study_JAVA\\MyHome\\Write_java\\My_Maven\\src\\main\\resources\\SimpleFactoryconfigTV.xml")); //获取包含品牌名称的文本节点 NodeList n1 = doc.getElementsByTagName("brandName"); Node classNode = n1.item(0).getFirstChild(); String brandName = classNode.getNodeValue().trim(); return brandName; } catch (Exception e) { e.printStackTrace(); return null; } } }
SimpleFactoryconfigTV.xml
<?xml version="1.0" encoding="UTF-8"?> <config> <brandName>Hisense</brandName> </config>
Client类
package simplefactory; 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()); } } }
运行结果:
简单工厂模式优点:
简单工厂模式缺点:
在以下情况下可以使用简单工厂模式:
标签:resources tno 影响 格式 详细 活性 源代码 ica ping
原文地址:https://www.cnblogs.com/zyx110/p/12536483.html