Factory three Brothers simple Factory mode (iv) _ Design mode

Source: Internet
Author: User
4 Improvement of the scheme

Sunny software company developers found that when creating a specific chart object, each replacement of a chart object would need to modify the parameters of the static factory method in client code, and the client code would be recompiled, which would violate the "open and closed" principle for the client, Is there a way to replace a specific product object without modifying the client code? The answer is yes, and here's a common way to implement this.

We can store the parameters of the static factory method in an XML or properties format configuration file, as shown in the following Config.xml:

<?xml version= "1.0"?>
<config>
	<chartType>histogram</chartType>
</config >

A tool class Xmlutil is used to read the string parameters in the configuration file, and the code for the Xmlutil class looks like this:

Import javax.xml.parsers.*;
Import org.w3c.dom.*;
Import org.xml.sax.SAXException;
Import java.io.*;

public class Xmlutil {
    //This method is used to extract the chart type from the XML configuration file and return the type name public
	static String Getcharttype () {
		try {
			// Create Document Object
			documentbuilderfactory dfactory = Documentbuilderfactory.newinstance ();
			Documentbuilder builder = Dfactory.newdocumentbuilder ();
			Document Doc;							
			doc = Builder.parse (new File ("Config.xml")); 
		
			Gets the text node that contains the chart type
			nodelist nl = doc.getelementsbytagname ("ChartType");
            Node Classnode = Nl.item (0). Getfirstchild ();
            String ChartType = Classnode.getnodevalue (). Trim ();
            return charttype;
        }   
       	catch (Exception e) {
           	e.printstacktrace ();
        	return null;}}}

After introducing the configuration file and tool class Xmlutil, the client code is modified as follows:

Class Client {public
	static void Main (String args[]) {
		Chart Chart;
		String type = Xmlutil.getcharttype (); Read the parameters in the configuration file
		chart = Chartfactory.getchart (type);//Create Product Objects
		Chart.display ();
	}

It is not difficult to find that in the above client code does not contain any information related to the specific chart object, if you need to replace the specific chart object, just modify the configuration file Config.xml, no need to modify any source code, in line with the "open and closed principle."

Thinking

Whether to add new specific products to the simple factory model is consistent with the "open and closed" principle. If not, what changes should be made to the original system.



5 simplification of simple factory model

Sometimes, in order to simplify simple factory patterns, we can combine abstract product classes with factory classes to move static factory methods into abstract product classes, as shown in Figure 3:

Figure 3 Simplified Simple Factory mode

In Figure 3, the client can create different types of product subclass objects from the static factory method of the product parent, depending on the parameters, which is also widely available in class libraries and frameworks such as JDK.

6 Simple Factory Model summary

The Simple factory model provides a specialized factory class for creating objects, leaving objects to be created and used by objects, and it is widely used in software development as one of the simplest factory patterns.

1. Main advantages

The main advantages of the simple factory model are as follows:

(1) The factory class contains the necessary judgment logic to decide when to create an instance of the product class, the client can dispense with the responsibility of directly creating the product object, but simply "consume" the product, and the simple factory model implements the separation of object creation and usage.

(2) The client does not need to know the specific product class name created, only need to know the specific product class corresponding to the parameters, for some complex class name, through a simple factory model can be a certain degree to reduce the user's memory.

(3) By introducing a configuration file, you can replace and add new specific product classes without modifying any client code, to some extent to improve the flexibility of the system.

2. Main shortcomings

The main disadvantages of the simple factory model are as follows:

(1) because the factory class concentrates all product creation logic, the responsibility is overweight, once does not work correctly, the entire system will be affected.

(2) The use of simple Factory mode will inevitably increase the number of classes in the system (introduced a new factory class), increasing the complexity of the system and understanding the difficulty.

(3) System expansion difficulties, once the addition of new products will have to modify the factory logic, in more types of products, it may cause the factory logic too complex, not conducive to the expansion and maintenance of the system.

(4) Simple factory model because of the use of static factory methods, the factory role can not form a hierarchy based on inheritance.

3. Applicable scene

You can consider using a simple factory pattern in the following situations:

(1) The factory class is responsible for creating fewer objects, and because fewer objects are created, the business logic in the factory method is not too complex.

(2) The client knows only the parameters of the incoming factory class and does not care about how to create the object.

Practice

Design a drawing tool that can create different geometries (such as circles, squares, triangles, and so on) using the simple factory pattern, each with a drawing draw () and erasing erase () two methods, requiring that when drawing an unsupported geometry, Tip a unsupportedshapeexception.

"Author: Liu Wei Http://blog.csdn.net/lovelion"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.