Java design pattern-Simple Factory mode

Source: Internet
Author: User
Tags dateformat locale

We all know that the factory is used to produce products, in the programming language so-called factory is to create an instanced object for us, the factory model is dedicated to the large number of common interfaces of the class instantiation, the program can dynamically

fixed which class to instantiate, Factory mode in the general book is considered to be divided into two, one is a simple Factory mode, another is the factory method mode.

1. Simple Factory mode structure

Look at the three types of roles in the diagram:

Abstract Product Role: The class that holds this role is typically the parent of the object created by the factory schema, and the abstract product role can be implemented with a Java interface or abstract class.

Specific product roles: all instances created in the factory are instance objects of the specific product role.

Factory role: This role is at the heart of the factory approach model, where the factory class dynamically decides which specific product object to create based on the incoming parameters, and has a close business relationship with the external class, which is often

Implemented by a Java class.

As a practical example, if we need an export function when we are doing the project, the system supports the ability to export files in Word, PDF, Excel and other formats. This is where we follow the simple factory model to

Design This program:

Abstract product Roles We implement an abstract class that contains an abstract export method that contains some basic properties, such as the file name.

Specific product roles: Exportword, Exportpdf, Exportexcel three Java classes inherit an abstract class, and then implement an abstract method in the parent class.

In the factory we pass the parameters passed by the client to determine the specific object to create which subclass of the instantiation.

2. Multi-level product structure

In the system we also encounter a more complex product structure, for example:


For this multi-layered product situation, the simple factory model is the status quo strategy, all use the same factory class, so there are advantages and disadvantages, the following is specific about its pros and cons:

Advantages: Simple design, the grade structure of the product class will not be reflected in the factory class to

Cons: First, this factory class contains all the product creation logic, forming an omniscient universal class, when this class problem, the client and the entire product chain is disconnected;

Second, when we want to add a product, we have to modify the factory class, the function of the development of more trouble, do not meet our design program "open-closed" principle.

Third, the simple Factory mode uses static methods as factory methods, static methods cannot be inherited by subclasses, and therefore, factory roles cannot be based on inherited hierarchy structures.

Note: "Open-closed" principle, a software should be open to external expansion, to modify the closure, that is, when we design a module, we should let this module has not been modified under the premise of extensible

Ability. Sounds awkward, for example in a book:

The Jade Emperor pacified Monkey King, will monkeys Fengwei wen, we will "Jade Emperor Management Heaven Order" as a software entity, then he gave the monkey seal officer, into his team, which is "open", on the other hand

This approach avoids the monkey destroying the heavenly order, which is "closed".

3. Application of simple Factory mode in Java

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

Look at the 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 a date that gets a Chinese format.

At first glance, Dateformat.getdateinstance () seems to be in the acquisition of their own instance object, actually not, look at the JDK source code very clearly see the DateFormat class is abstract class, is unable to instantiate,

so let's look at a What's the situation?

GetDateFormat source code 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 saw that three getdateformat methods eventually called the Get () method, and we followed the Get method:

    /** * 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 are 2 * @param datestyle a VA Lue from 0 to 3 indicating the time format, * ignored if flags are 1 * @param flags either 1 for a time format, 2 F or a date format, * or 3 for a date/time format * @param loc the locale for the format */private static Da Teformat get (int timestyle, int datestyle, int flags, Locale loc) {if (Flags &am P 1)! = 0) {if (Timestyle < 0 | | Timestyle > 3) {throw new IllegalArgumentException ("Illeg            Al Time Style "+ Timestyle);        }} else {timestyle =-1; if ((Flags & 2)! = 0) {if (Datestyle < 0 | | Datestyle > 3) {throw new Illeg            Alargumentexception ("Illegal date style" + Datestyle); }        } else {datestyle =-1; } try {//Check whether a provider can provide an implementation that's closer//to the RE            Quested 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"); }    }
See, the end result is an instantiated object of the SimpleDateFormat class, because SimpleDateFormat is a subclass of DateFormat, so the return type of the Getdateinstance () method can be

DateFormat class, which is also a manifestation of polymorphism.

Example summary: Due to the use of the Simple Factory mode, the client does not care about how to create and compose the objects returned by the factory method, which objects are instantiated by the factory method and how the objects are instantiated specifically.

Details hidden to make the use of these objects easier. Unlike the general simple factory model, the above example combines the factory role and the abstract product role into a class dateformat, which is abstract

Product roles are responsible for the creation of specific products, which is a special case of the simple factory model

Later think of what application examples to add .....






Java design pattern-Simple Factory mode

Related Article

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.