简单工厂

参考《设计模式的艺术软件开发人员内功修炼之道》-刘伟 著

实验目的

工厂方法是一种常见的制造对象的方法(其他,如new新对象,反射,clone等),其中简单工厂通过一个工厂类,根据入参生产出对应的子对象。

实验代码

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/****************** SimpleFactory ********************/
abstract class Chart {
    public void display() {

    }
}

class HistgramChart extends Chart {
    public HistgramChart() {
    }

    public void display() {
        System.out.println("display HistgramChart ...");
    }
}

class LinerChart extends Chart {
    public LinerChart() {

    }

    public void display() {
        System.out.println("display LinerChart ...");
    }
}

class PieChart extends Chart {
    public PieChart() {

    }

    public void display() {
        System.out.println("display PieChart ...");
    }
}

class SimpleFactory {
    public static Chart getChart(String type) {
        Chart chart = null;
        switch (type) {
        case "Histgram":
            chart = new HistgramChart();
            break;
        case "Liner":
            chart = new LinerChart();
            break;
        case "Pie":
            chart = new PieChart();
            break;
        default:
            chart = new HistgramChart();
        }
        return chart;
    }
}

/***************** Improved SimpleFactory *********************/
class XMLUtil {
    private static DocumentBuilderFactory dFactory;
    private static DocumentBuilder dBuilder;
    private static Document doc;

    private static void init() {
        dFactory = DocumentBuilderFactory.newInstance();
        try {
            dBuilder = dFactory.newDocumentBuilder();
            doc = dBuilder.parse(new File("config.xml"));
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public static String getChartType() {
        init();
        NodeList nl = doc.getElementsByTagName("chartType");
        Node node = nl.item(0).getFirstChild();
        String chartType = node.getNodeValue().trim();
        return chartType;
    }

    public static void getChartConfig() {
        init();
        NodeList nl = doc.getElementsByTagName("chartInit");
        NodeList nl_1 = nl.item(0).getChildNodes();
        for (int index = 0; index < nl_1.getLength(); index++){
            Node node = nl_1.item(index);
            if(node.getNodeName().equalsIgnoreCase("chartunit")){
                String chartClass = null ,chartString = null;
                NodeList innerNL = node.getChildNodes();
                for(int innerIndex = 0; innerIndex < innerNL.getLength(); innerIndex++){
                    Node innerNode = innerNL.item(innerIndex);

                    if(innerNode.getNodeName().equalsIgnoreCase("chartClass")){
                        chartClass = innerNode.getFirstChild().getNodeValue();
                    }
                    if(innerNode.getNodeName().equalsIgnoreCase("chartString")){
                        chartString =  innerNode.getFirstChild().getNodeValue();
                    }
                    if(chartClass != null && chartString != null)
                    ImprovedSimpleFactory.putChart(chartClass, chartString);
                }
            }

        }


    }
}

class ImprovedSimpleFactory {
    private static Map<String,String> chartMap = new HashMap<String,String>();
    public static Chart getChart(String type) {
        /* System.out.println("chartMap's size is " + chartMap.size());
         for(Map.Entry<String, String> entry : chartMap.entrySet()){
              System.out.println("key is " + entry.getKey() + " : value is " + entry.getValue());
         }*/
         String chartClass = chartMap.get(type);
      //   System.out.println("type is " + type);
         if(chartClass != null){
             try {
                Chart chart = (Chart)Class.forName(chartClass).newInstance();
                return chart;
            } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
         }
         return null;
    }
    public static void putChart(String chartClass, String chartType){
        chartMap.put(chartType,chartClass);
    }
}



public class SimpleFactoryTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("================SimpleFactory===================");
        Chart histgramChart = SimpleFactory.getChart("Histgram");
        histgramChart.display();
        Chart linerChart = SimpleFactory.getChart("Liner");
        linerChart.display();
        Chart pieChart = SimpleFactory.getChart("Pie");
        pieChart.display();
        System.out.println("================ImprovedSimpleFactory===================");
        String chartType = XMLUtil.getChartType();
        XMLUtil.getChartConfig();
        Chart chart = SimpleFactory.getChart(chartType);
        chart.display();
        Chart improvedChart = ImprovedSimpleFactory.getChart(chartType);
        improvedChart.display();
    }

}

结果输出

================SimpleFactory===================
display HistgramChart ...
display LinerChart ...
display PieChart ...
================ImprovedSimpleFactory===================
display LinerChart ...
display LinerChart ...

总结

  • 一般一个工厂负责一类(包含子对象)的创建,初始化工作
  • 将创建对象的工作交给工厂,使业务逻辑模块更专注于业务逻辑的实现,分离对象的创建和使用
  • 简单工厂适用于创建相对少的对象,扩展性差
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值