Java design mode: Factory mode

Source: Internet
Author: User

Questions raised

The Java factory model is very similar to the real-life model of the factory. What is the factory used for? Of course it is used to generate products. So the key point in the Java Factory model is how to describe the relationship between the 2 roles of a product and a factory.

Let's take a closer look at the different relationships and the corresponding design patterns.

1) Single product line, factory produces only one type of product

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/1055141/201704/ 1055141-20170417224329212-1678195478.png "style=" Border:none;height:auto; "/>

Let us simply conceive of a simple factory production model, since there is only one product, that only need a workshop, a workshop to produce three different kinds of cars. OK, here's a look at the simple factory design pattern.

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/1055141/201704/ 1055141-20170417224355899-859322894.png "style=" Border:none;height:auto; "/>

Define car interface: Icar.javapublic interface ICar {}
public class Topcar implements ICar {}
public class Midcar implements ICar {}
public class Lowcar implements ICar {}

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Border:none; "/>

public class carsimplefactory {    public static final  string toptype =  "TopType";     public static final string  MIDTYPE =  "Midtype";    public static final string  lowtype =  "Lowtype";     private carsimplefactory () {             }    public static ICar  Create (String mark) {        icar obj = null;         if (Mark.equals (toptype)) {             obj = new topcar ();         }        else if (Mark.equals (MIDTYPE)) {         &Nbsp;   obj = new midcar ();         }         else if (Mark.equals (lowtype)) {             obj = new lowcar ();         }        return obj;     }}

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Border:none; "/>

Simple factory Functional class writing steps:

1. Writing Abstract product interfaces

2. Writing specific product sub-categories

3. Write the factory class. The characteristic of a simple factory class, it is a concrete class, non-interface type abstract class. There is an important create () method and create the required product with IF...ELSE or switch development. Because this simple factory class can be implemented as a tool class, it is possible to use static methods directly, if necessary, or even to privatize the construction method.

Let's consider a situation where the factory expands! can be processed to produce super-high-grade cars. How do you change it in the production mode above?

1) Added Icar sub-class supercar

2) Modify the Create () method in the factory class Simplecarfactory to add the Judgment branch.

The addition of subclass supercar is inevitable, but can we not modify the factory class?

Or from another point of view, the production of several different kinds of products on a production line, so that we also need to classify each product to determine the category. Of course, if only 2 species are to be differentiated, it is certainly not a problem, but if there are multiple types to differentiate? Obviously, you can't produce many kinds of products on one line! That means we need a production line for every kind of product. This is called the factory model!

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/1055141/201704/ 1055141-20170417224658774-173264373.png "style=" Border:none;height:auto; "/>

Public abstract class Abstractfactory {public abstract ICar Create ();}

650) this.width=650; "id=" code_img_closed_fa8cb3de-907c-4613-851e-c050533cd21b "src="/img/jia.gif "style=" border: none; "/> View Code

650) this.width=650; "id=" Code_img_closed_13ea3324-b342-48fb-82c4-ee164edefe08 "src="/img/jia.gif "style=" border: none; "/> View Code

650) this.width=650; "id=" Code_img_closed_48ca85fa-0cc4-40af-aa9a-e3cb0aff88f9 "src="/img/jia.gif "style=" border: none; "/> View Code

and the observation code, as long as there are icar.java,abstractfactory.java these two files, other specific product class, factory source files are not, compile can also pass.

For abstractfactory, you can define it as an abstract class or as an interface. The Create () here is an abstract method, without parameters, to indicate that a specific product is created in a specific subclass factory.

The main feature of the factory approach is that when the requirements analysis changes, only the corresponding classes need to be added and removed, rather than modifying the existing classes. For example, to add ultra-high-grade cars, you only need to add supercar and superfactory two classes. So the factory method is easier to develop and maintain the software two times.

Of course, a factory is likely to produce more than one product. Look at the multi-product line below.

2) Multiple product lines with the same characteristics

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/1055141/201704/ 1055141-20170417224919259-1811132204.png "style=" Border:none;height:auto; "/>

UML Diagram and Factory mode basically no difference, here is no longer draw.

In general, the simple factory and factory model are the yield strains, and for the above structure, it is called abstract factory. But in essence, abstract factories and factory models are unified. There is no more telling.

3) Multi-product system, some of the same features

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/1055141/201704/ 1055141-20170417225003790-666615638.png "style=" Border:none;height:auto; "/>

Public abstract class Abstractfactory {/** * Multi-product series, cars and buses are high, mid-range type, cars have low-grade type, and buses do not */}
Public abstract class AbstractFactory1 extends Abstractfactory {public abstract ICar createcar ();   Generated car object public abstract IBus Createbus (); Generate Bus Object}
Public abstract class AbstractFactory2 extends Abstractfactory {public abstract ICar createcar ();//Generate Car Object}

Here's a look at Abstractfactory,abstractfactory1,abstractfactory2.

1) Cars and buses with the same characteristics are placed in the same factory

2) This class is also an abstract class, indicating that "features are multiple". Here the characteristic means "high middle and low".

Factory model about here, see here, believe that a lot of people have one, the factory model is the same. However, the individual feels that no matter what the design pattern looks like it is easy to understand well. However, when faced with problems need to analyze the design of their own time, then suddenly lost the clue.

There are about 2 reasons, one is not very familiar with the design pattern and understanding, and the second course is not practiced. Gossip does not say much, let us practice a wave under the fencing.

Example: Writing a read file function. Read text files, including gbk,utf-8. encoded text files, requiring full-text content; Reading image files, including bmp,gif,jpg files, requires the acquisition of the image width, length, and the three primary color information for each point.

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/1055141/201704/ 1055141-20170417225217634-1489298231.png "style=" Border:none;height:auto; "/>

The code is as follows:

Reading a text file method requires two parameters: file name and encoding, while reading an image file requires a parameter: file name. Depending on the test instructions, the two types of read file return values vary.

How to use the interface to mask the number of parameters, return value type difference, is the key to define the interface.

Public interface Iread<t> {//How to use the interface mask method parameter number, return the difference of value type, this is the key that defines the interface T read (String ... in);}

650) this.width=650; "id=" code_img_closed_a76a8422-8160-47d3-a900-92106d565f96 "src="/img/jia.gif "style=" border: none; "/> View Code

650) this.width=650; "id=" Code_img_closed_c2b4136f-1920-4bc6-a341-4a53bdbb8eba "src="/img/jia.gif "style=" border: none; "/> View Code

650) this.width=650; "id=" code_img_closed_2e68c5a9-6674-4c58-a738-f29ed525130a "src="/img/jia.gif "style=" border: none; "/> View Code

Public abstract class Abstractfactory {//define abstract Factory public abstract iread Create ();}
public class Textfactory extends Abstractfactory {public Iread Create () {return new Textread (); }}
public class Imagefactory extends Abstractfactory {public Iread Create () {return new Imageread (); }}

For the above abstract factory class is actually not perfect, how to choose the specific factory class is not reflected. There are two ways to resolve this. One is to add a selection branch like a simple factory. The second is to use reflection.

The following code is using the reflection technique

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Border:none; "/>

public abstract class abstractfactory {    public abstract  Iread create ();     static abstractfactory create (String className) {         AbstractFactory factory = null;         try{             class c = class.forname (ClassName);             factory =  (abstractfactory) c.newinstance ();         }        catch  (Exception ex) {             ex.printstacktrace ();         }        return factory;     }}

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Border:none; "/>

The use of reflective technology enables a more flexible automatic plant selection function. When adding a new factory class, you do not need to modify the Abstractfactory class.


Java design mode: Factory mode

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.