Java Advanced design mode two-----Factory mode

Source: Internet
Author: User

Objective

In the previous article, we studied the singleton model, and introduced several methods and the optimal method of the single-case pattern creation. This article introduces the factory model in design mode, which is divided into simple Factory mode, factory method and abstract Factory mode.

Simple Factory mode

The Simple Factory mode is the creation mode, also called the Static factory method mode. A simple factory model is a factory object that determines which product class instances are created. The call simply tells the factory class what type is required, and the factory class returns the subclass of the desired product class factory. Can be said to be the simplest of the factory model.

For example, we often play games on the computer, we just need to tell the computer what game we want to play, the computer will open the game, we do not need to care about how the game works.
We can explain this in the following code.

We first create a total game class interface, including a game-playing method, and then the respective game class to inherit the class and implement the method of the class, and finally create a project class based on different games to create objects.
Then the code is implemented as follows:

code example:

    private static final String LOL="LOL";     private static final String DNF="DNF";     public static void main(String[] args) {        Game game= ComputerFactory.playGame(LOL);        Game game2= ComputerFactory.playGame(DNF);        game.play();        game2.play();    }}interface Game{    void play();}class LOL implements Game{    @Override    public void play() {        System.out.println("正在玩LOL...");    }   }class DNF implements Game{    @Override    public void play() {        System.out.println("正在玩DNF...");    }   }class ComputerFactory{    private static final String LOL="LOL";     private static final String DNF="DNF";      public static Game playGame(String game){         if(LOL.equalsIgnoreCase(game)){             return new LOL();         }else if(DNF.equalsIgnoreCase(game)){             return new DNF();         }         return null;     }  

Output Result:

正在玩LOL...正在玩DNF...

After we implemented this function using the simple factory model, we found that we implemented the instantiation of the game class into the factory class, hidden the details of the object creation, and did not need to know how to play it, just to know that the factory class was called. And it's easy to switch because you just need to change the type value passed by the factory class.
But we also found a problem, if we need to add a game class, then we need to define a new interface, and then also to add a Judgment branch in the factory class, if a small number of good, but a lot of things are more troublesome, and this also violates the open-closed principle.

Factory method Mode

The factory method pattern is one of the most commonly used design patterns in Java and belongs to the creation pattern. Define an interface that creates an object so that its subclasses decide which factory class to instantiate, and the Factory mode defers its creation process to subclasses.

In the simple factory model, we found that when adding subclasses, the corresponding need to add a branch of judgment in the factory class is against the open-closed principle. And the factory method pattern is the main solution to this problem.

Here is the example of playing the game above, except that each game is implemented by its own game factory class. The main difference is that a factory class becomes more than one, reducing the coupling degree. If you add a new game class, you just need to add a new factory class, and follow the open-close principle perfectly.

After you change the above code, the corresponding code is implemented as follows:

code example:

    private static final String lol= "LOL";     private static final String dnf= "DNF";     private static final String wow= "WOW";        public static void Main (string[] args) {Game game3=new lolfactory (). PlayGame (LOL);        Game game4=new dnffactory (). PlayGame (DNF);        Game game5=new wowfactory (). PlayGame (WOW);        Game3.play ();        Game4.play ();           Game5.play (); }interface game{void Play ();    Class LOL implements game{@Override public void Play () {System.out.println ("playing LOL ...");    }}class DNF implements game{@Override public void Play () {System.out.println ("playing DNF ...");    }}class Wow implements game{@Override public void Play () {System.out.println ("playing wow ..."); }}interface computerfactory2{Game PlayGame (String game);}     Class Lolfactory implements computerfactory2{@Override public Game playGame (String game) {return new LOL (); }}class Dnffactory implements computerfactory2{   @Override public Game PlayGame (String game) {return new DNF (); }}class Wowfactory implements computerfactory2{@Override public Game playGame (String game) {return new WOW (    ); }}

Output Result:

正在玩LOL...正在玩DNF...正在玩WOW...

We can see that after using the factory method pattern, our code is clearer, the extensibility becomes higher, if you want to add a product, just extend a factory class. However, the complexity is added to the system, and each time a product is added, a specific class and object is added to implement the factory class.
So be aware of the use of this mode.
Using this pattern to compare classic use cases is the famous Hibernate framework in the Select database dialect this block. However, if the simple new object is not used, it will increase the complexity of the system if used instead.

Abstract Factory mode

Abstract Factory mode is the creation of other factories around a super factory. The Super Factory is also known as a factory in other factories. This type of design pattern belongs to the Create pattern, which provides an optimal way to create an object. That is to provide an interface that creates a series of related or interdependent objects without specifying their specific classes.

Abstract Factory mode is more complex and more difficult to understand than the factory method pattern, but it is easier to expand.
Abstract factory models classify the same class of product subclasses into one class, let them inherit the same abstract subclass, then treat them as a group, and then group the groups into a family.
For example, or the above game, we can play LOL and wow as a PVP type of game, you can also DNF and wow as a PVE Type of game.

Then the code for the corresponding change is as follows:

code example:

    private static final String lol= "LOL";     private static final String dnf= "DNF";     private static final String wow= "WOW";        public static void Main (string[] args) {ComputerFactory3 cf3=new pvpfactory ();        Cf3.playgame (). Play ();        Cf3.playgame2 (). Play ();        ComputerFactory3 cf4=new pvefactory ();        Cf4.playgame (). Play ();             Cf4.playgame2 (). Play (); }}interface game{void Play ();    Class LOL implements game{@Override public void Play () {System.out.println ("playing LOL ...");    }}class DNF implements game{@Override public void Play () {System.out.println ("playing DNF ...");    }}class Wow implements game{@Override public void Play () {System.out.println ("playing wow ...");     }}interface computerfactory3{Game playGame (); Game playGame2 ();}    Class Pvpfactory implements computerfactory3{@Override public Game playGame () {return new LOL (); } @Override Public Game PlaygaMe2 () {return new WOW ();    }}class Pvefactory implements computerfactory3{@Override public Game playGame () {return new DNF ();    } @Override Public Game playGame2 () {return new WOW (); }}

Output Result:

正在玩LOL...正在玩WOW...正在玩DNF...正在玩WOW...

In the abstract Factory mode, you can do without knowing what the product is, just know which factory class is on the line. We can also design them together according to the common characteristics of the subclasses, forming a group of the same type, which can be conveniently called directly. But relative, product family is more difficult to expand, add a product, need to add corresponding interface and implement class. For example, a brand of mobile phones, there are different series, each series has a different model, if only to increase the model, it is easier, but relative, to increase a series is more troublesome.
So we are using the Abstract Factory mode, also need the corresponding actual scene to use.

Other music recommendations

In this impetuous society, will also be affected by it, so can not calm down. So go out and walk, quietly listen to the music, will feel the mood slowly soothing up, the whole person will be relaxed a lot. So I shared a piece of pure music, hoping to bring ease and smile to the reader.

<iframe frameborder= "No" border= "0" marginwidth= "0" marginheight= "0" width=330 height=86 src= "//music.163.com/ Outchain/player?type=2&id=27580689&auto=0&height=66 "></iframe>

Original is not easy, if feel good, hope to give a recommendation! Your support is my greatest motivation for writing!
Copyright Notice:
Empty Realm
Blog Park Source: http://www.cnblogs.com/xuwujing
CSDN Source: HTTP://BLOG.CSDN.NET/QAZWSXPCM
Personal blog Source: http://www.panchengming.com

Java Advanced design mode two-----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.