其他分享
首页 > 其他分享> > 【设计模式】简单工厂模式

【设计模式】简单工厂模式

作者:互联网

设计模式入门,简单工厂模式初体验:

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


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