Java design mode-Factory mode

Source: Internet
Author: User

Preface

Factory mode is a relatively common mode of creation. Sometimes. Maybe you used the Factory mode and you didn't know you were using it. At least I feel like the first simple factory model that you are already very familiar with.

And it's often used. If you don't believe, keep looking down.


Copyright Notice

Copyright belongs to all authors.
Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.
This article Coding-naga
Published: April 14, 2016
This article link: http://blog.csdn.net/lemon_tree12138/article/details/46225213
Source: CSDN
Lots of other content: Classification >> Design Patterns


Simple Factory mode (easy Factory pattern)

Starting with the simple factory model, we need to know what the purpose of the factory model is. The purpose of the factory model is to extend the program.

And for a simple factory model. It is designed to allow programs to have a better encapsulation, reducing the degree of coupling between program modules.

For a simple factory model, it can actually be understood as a tool class for creating objects. The form of a tool class that can mimic such as the following code is written:

public class Simplefactory {public    Object Create (class<?> clazz) {        if (Clazz.getname (). Equals ( Plane.class.getName ())) {            return Createplane ();        } else if (Clazz.getname (). Equals (Broom.class.getName ())) {            return Createbroom ();        }                return null;    }        Private Broom Createbroom () {        return new broom ();    }        Private Plane Createplane () {        return new Plane ();}    }
test code such as the following:
public class Factorytest {public    static void Main (string[] args) {        //simple Factory mode test        simplefactory simplefactory = New Simplefactory ();        Broom broom = (broom) simplefactory.create (broom.class);        Broom.run ();    }}
As previously mentioned, the Simple factory model. is to create a tool class that creates objects. In this tool class, we are able to do some other things. For example, the initialization of an object.

This avoids the large amount of code that initializes the object (assuming there is a lot of code) in the constructor.


Factory method Pattern (Factory mode)

Before we talked about simple Factory mode, in simple Factory mode, we created a class of similar tools to create the corresponding detailed class object. Because it is too simple, there is no specification. So. Here to do some proper encapsulation of it.

Let's take a look at the definition of the factory method pattern. The factory method pattern defines an interface to create an object, but the subclass determines which one to instantiate.

The factory method defers the instantiation of the class to the subclass.

(Definition from "Head first design mode")


Figure-1 Factory method mode

Abstract Factory:

Our abstract factory can be similar to this:

Public abstract class Vehiclefactory {public    abstract moveable Create ();}
Detailed factory:

The code is so simple and beautiful. And it has a detailed implementation of the factory class:

public class Broomfactory extends Vehiclefactory {    @Override public    moveable Create () {        return new broom (); c6/>}}
this detailed implementation of the factory tells us. Here, you can create a broom object by means of the Create () method.

We can understand their relationship in this way: there is a big factory which is vehiclefactory. Vehiclefactory Factory also has a lot of production workshop, one of which is broomfactory.

Our detailed products are produced through these workshops.

Abstract Product Interface:

When it comes to products, we can first imagine what the nature of these detailed products would look like. We can define them like this:

Public interface Moveable {public    void run ();
Detailed Products:

Well, here are some products that can run (move). As far as the Broomfactory production Workshop is concerned. It is responsible for producing broom.

This broom is a property with moveable. Then its implementation can be written like this:

public class Broom implements moveable {    @Override public    void Run () {        System.out.println ("I am broom. I'm flying ..." );    }}
function test:

We have a factory and we know what the factory is going to produce. So let's make a broom to try it out:

Vehiclefactory factory = new Broomfactory (); Moveable moveable = Factory.create (); Moveable.run ();
so I produced a broom. Isn't so easy?

Abstract Factory mode (Factory pattern)

From the structure in the factory method above, we can see that the detailed factories A and B are two completely independent. Both are the subclasses of the abstract factory, no matter what the other intersection.

However, suppose we have a requirement that the detailed factories A and b need to produce a number of different products of the same type. Then we can try the abstract factory model.

Let's see how the Abstract factory pattern is defined: Provides an interface for creating a set of related or interdependent objects without specifying their detailed classes. The same in the following structure diagram, we are able to better explain this definition. Our abstract factory includes a series of methods to construct an abstract product, and the implementation of the detailed product is placed in a detailed factory (A and B in the figure).


Figure-2 Abstract Factory mode

Now let's look at how the code is implemented.

Abstract Factory:

Public abstract class Abstractfactory {public    abstract flyable createflyable ();        public abstract moveable createmoveable ();        Public abstract writeable createwriteable ();}

Detailed factory:As can be seen from the code of the abstract factory, abstract factories are merely "producing" some abstract things.

Somewhat similar to the feeling of the underlying mechanism. Now let's take a look at the detailed factory implementation.

public class Factory1 extends Abstractfactory {    @Override public    flyable createflyable () {        return new Aircraft ();    }    @Override Public    Moveable createmoveable () {        return new Car ();    @Override Public    writeable createwriteable () {        return new Pen ();}    }

Abstract Product Interface:in the detailed factory, we will be able to produce a number of detailed products. This is the aircraft, Car, Pen. Abstract product interfaces such as the following.

Public interface flyable {public    void fly (int height);}

Detailed Products:The detailed product is to implement this interface. and implement the methods, such as the following:

Public class aircraft implements flyable {    @Override public    void Fly (int height) {        System.out.println (" I am a passenger plane, my current flight height is: "+ height +" km. ");    }}

function test:with these things, let's make a good production of some products.
public class Factorytest {public    static void Main (string[] args) {        Abstractfactory factory = new Factory1 ();        flyable flyable = factory.createflyable ();        Flyable.fly (1589);                Moveable moveable = factory.createmoveable ();        Moveable.run (87.6);                Writeable writeable = Factory.createwriteable ();        Writeable.write ("Hello World");}    }
Now let's see if the result is the same as we thought.

Figure-3 abstract Factory mode execution result diagram

Summary

The above is the basic implementation of the factory model and detailed description.

Includes simple Factory mode, factory method mode, abstract Factory mode.

We are able to choose the right factory model based on demand.

The following is a GitHub link for all the code in this article.


GitHub Source code links

Https://github.com/William-Hai/DesignPatternCollections

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.