【设计模式】简单工厂模式
作者:互联网
设计模式入门,简单工厂模式初体验:
-
类图
-
Tv接口
package simpleFactory;
/**
* @author jitwxs
* @date 2021年05月13日 14:52
*/
public interface Tv {
public void play();
}
实现类
package simpleFactory;
/**
* @author jitwxs
* @date 2021年05月13日 15:11
*/
public class TCL implements Tv{
@Override
public void play() {
System.out.println("TCL电视正在播放");
}
}
package simpleFactory;
/**
* @author jitwxs
* @date 2021年05月13日 14:53
*/
public class Haier implements Tv{
@Override
public void play() {
System.out.println("海尔电视正在播放");
}
}
工厂
package simpleFactory;
/**
* @author jitwxs
* @date 2021年05月13日 14:54
*/
public class SimpleFactory {
public static Tv produce(String brand){
if (brand.equalsIgnoreCase("haier")){
System.out.println("海尔电视正在生产");
return new Haier();
}else if (brand.equalsIgnoreCase("hessien")){
System.out.println("海信电视正在生产");
return new Hessien();
}else if (brand.equalsIgnoreCase("tcl")){
System.out.println("TCL电视正在生产");
return new TCL();
}
return null;
}
}
xmlUTils
package simpleFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.*;
import java.io.File;
/**
* @author jitwxs
* @date 2021年05月13日 14:57
*/
public class XmlUtils {
public static String getBname(){
try{
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
Document doc;
doc = builder.parse(new File("simpleFactory.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文件
<?xml version="1.0"?>
<config>
<brandName>tcl</brandName>
</config>
测试
package simpleFactory;
/**
* @author jitwxs
* @date 2021年05月13日 15:05
*/
public class Test1 {
public static void main(String[] args) throws Exception{
Tv tv;
String brandName = XmlUtils.getBname();
tv=SimpleFactory.produce(brandName);
tv.play();
}
}
标签:return,05,jitwxs,package,模式,工厂,simpleFactory,设计模式,public 来源: https://blog.csdn.net/m0_46495243/article/details/116751393