JAVA design pattern-simple factory pattern

Source: Internet
Author: User

JAVA design pattern-simple factory pattern

We all know that factories are used to produce products. In programming languages, the so-called factories create instantiated objects for us. The factory mode is dedicated to instantiating a large number of classes with common interfaces, the program can dynamically decide

Determine which class to instantiate. The factory mode is generally considered to be divided into two types: simple factory mode and factory method mode.

1. Simple factory mode structure

Examples/examples/zsvrGt73Hyau/samples + nP88DgwLTKtc/WoaM8L3A + samples/samples + 3 bSryOuyzsG/samples + 38zlsvrGt7bUz/samples + samples/bP7sS /clusters/queues + queues/queues + nP88DgwLTKtc/Wo6yz6c/queues + queues/queues + 7PGoaM8L3A + queues/B/Nu6e2y7Srtd25/queues + 1zbPW0M7Sw8e7ubvh0/a1vbj8zqq4tNTTtcSy + sa3veG5uSy + Weight = "http://www.2cto.com/uploadfile/Collfiles/20140915/20140915093918160.jpg" alt = "\">

To address this multi-level product situation, the simple factory model adopts a policy that remains unchanged and uses the same factory class. This method has advantages and disadvantages, the following describes its advantages and disadvantages:

Advantage: The design is simple, and the hierarchical structure of the product class is not reflected in the factory class.

Disadvantages: first, this factory class contains the creation logic of all products, forming an all-embracing class. When this class fails, the connection between the client and the entire product chain is interrupted;

Second, when we want to add a product, we must modify the factory class, which is difficult to expand functions and does not meet the "open-close" principle of our design program.

Third, the simple factory mode uses the static method as the factory method. The static method cannot be inherited by sub-classes. Therefore, the factory role cannot be based on the inherited hierarchy.

Note: In the "open-close" principle, a software should be open for external development and closed for changes. That is to say, when designing a module, this module should be extended without being modified

Capability. It sounds awkward. Here is an example written in the book:

Yu Di Zhao an Monkey King, sealing monkeys as Ma Wen, and we regard "Yu Di manages tianting order" as a software entity. Then he seals monkeys and adds them to his team, this is "open", on the other hand

This practice avoids monkeys from damaging the order of heaven, which is "closed".

3. Application of simple factory mode in Java

A typical example is the DateFormat class that we usually use to format dates.

Read a piece of code:

import java.text.DateFormat;import java.text.ParseException;import java.util.Date;import java.util.Locale;public class SimpleFactoryDemo1 {public static void main(String[] args) throws ParseException {Locale locale =Locale.CHINA;Date d=new Date();System.out.println(d);System.out.println(DateFormat.getDateInstance(DateFormat.DEFAULT,locale).format(d)); }}
This code is used to obtain a date in Chinese format.

At first glance, DateFormat. getDateInstance () seems to be obtaining its own instance object. In fact, it is not. From the JDK source code, it is clear that the DateFormat class is an abstract class and cannot be instantiated,

So let's take a look at what the situation is?

The source code of getDateFormat is as follows:

    /**     * Gets the date formatter with the default formatting style     * for the default locale.     * @return a date formatter.     */    public final static DateFormat getDateInstance()    {        return get(0, DEFAULT, 2, Locale.getDefault());    }    /**     * Gets the date formatter with the given formatting style     * for the default locale.     * @param style the given formatting style. For example,     * SHORT for "M/d/yy" in the US locale.     * @return a date formatter.     */    public final static DateFormat getDateInstance(int style)    {        return get(0, style, 2, Locale.getDefault());    }    /**     * Gets the date formatter with the given formatting style     * for the given locale.     * @param style the given formatting style. For example,     * SHORT for "M/d/yy" in the US locale.     * @param aLocale the given locale.     * @return a date formatter.     */    public final static DateFormat getDateInstance(int style,                                                 Locale aLocale)    {        return get(0, style, 2, aLocale);    }
We can see that all the three getDateFormat Methods finally call the get () method. Let's track this get method again:

    /**     * Creates a DateFormat with the given time and/or date style in the given     * locale.     * @param timeStyle a value from 0 to 3 indicating the time format,     * ignored if flags is 2     * @param dateStyle a value from 0 to 3 indicating the time format,     * ignored if flags is 1     * @param flags either 1 for a time format, 2 for a date format,     * or 3 for a date/time format     * @param loc the locale for the format     */    private static DateFormat get(int timeStyle, int dateStyle,                                  int flags, Locale loc) {        if ((flags & 1) != 0) {            if (timeStyle < 0 || timeStyle > 3) {                throw new IllegalArgumentException("Illegal time style " + timeStyle);            }        } else {            timeStyle = -1;        }        if ((flags & 2) != 0) {            if (dateStyle < 0 || dateStyle > 3) {                throw new IllegalArgumentException("Illegal date style " + dateStyle);            }        } else {            dateStyle = -1;        }        try {            // Check whether a provider can provide an implementation that's closer             // to the requested locale than what the Java runtime itself can provide.            LocaleServiceProviderPool pool =                LocaleServiceProviderPool.getPool(DateFormatProvider.class);            if (pool.hasProviders()) {                DateFormat providersInstance = pool.getLocalizedObject(                                                    DateFormatGetter.INSTANCE,                                                    loc,                                                     timeStyle,                                                    dateStyle,                                                    flags);                if (providersInstance != null) {                    return providersInstance;                }            }            return new SimpleDateFormat(timeStyle, dateStyle, loc);        } catch (MissingResourceException e) {            return new SimpleDateFormat("M/d/yy h:mm a");        }    }
As you can see, the final returned object is the instantiated object of the SimpleDateFormat class. Because SimpleDateFormat is a subclass of DateFormat, the return type of the getDateInstance () method can be

DateFormat class, which is also a manifestation of polymorphism.

Instance Summary: Because the simple factory mode is used, the client does not need to care about how to create and construct the objects returned by the factory method. What objects will be instantiated by the factory method and how to instantiate these objects?

The details are hidden to simplify the use of these objects. Unlike the general simple factory model, the factory role and the abstract Product role in the preceding example are combined into a DateFormat class, that is, the abstract

The product role is responsible for creating specific products, which is also a special case of the simple factory model.

What application instances do you want to add ............






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.