Which scenarios in the actual development need to use Factory mode?

Source: Internet
Author: User

The factory method mode allows the system to introduce new products without modifying the factory role.

    1. Factory mode

    2. Simple Factory mode

    3. Abstract Factory mode

Which cases will be used in the actual development? Why do I feel like I'm developing a few of these design patterns now?

Reply content:

The factory method mode allows the system to introduce new products without modifying the factory role.

    1. Factory mode

    2. Simple Factory mode

    3. Abstract Factory mode

Which cases will be used in the actual development? Why do I feel like I'm developing a few of these design patterns now?

I'm going to start by saying that I'm seeing examples of factory models:

In the general MVC framework, there is a basic DB database operation class
I call it DB class, there is a Basemodel class to inherit DB Class
Basemodel is the base class for all frame model and needs to inherit Basemodel
Basemodel has a DB class of additions and deletions to check the method, Basemodel is actually the database factory, different models inherit Basemodel, there is the operation of different data table object instances, so that a basic class to complete the instantiation of various data table objects, Like a factory, passing different table names returns you to different objects.
My understanding is this, such as the mistake, also please forgive and treatise.

The

Factory mode is a pattern for instantiating objects and is a way of replacing the new operation with a factory method. Factory mode is everywhere in the Java project, because the factory pattern is equivalent to the creation of new instance objects, such as in our system often need to log, if you create a logger instance of the initialization work can be a long code, may be initialized, assignment, query data and so on, Will cause the code to be bloated and ugly.

 private static Logger Logger = Loggerfactory.getlogger (Mybusinessrpc.class); public static Logger GetLogger (String name) {iloggerfactory iloggerfactory = Getiloggerfactory (); return Iloggerfactory.getlogger (name); }public static Iloggerfactory getiloggerfactory () {if (initialization_state = = uninitialized) {Initialization_st ATE = ongoing_initialization; Performinitialization (); } switch (initialization_state) {case Successful_initialization:return Staticloggerbinder.getsingleton (). Getloggerfactory (); Case Nop_fallback_initialization:return Nop_fallback_factory; Case Failed_initialization:throw New IllegalStateException (UNSUCCESSFUL_INIT_MSG); Case Ongoing_initialization://Support re-entrant behavior. See also http://bugzilla.slf4j.org/show_bug.cgi?id=106 return temp_factory; } throw new IllegalStateException ("Unreachable Code"); }

If you want to understand the factory model, you can't be unaware of the simple factory model.

 switch ($type) {       case '存款职员': $man = new Depositer;       break;      case '销售': $man = new Marketer;       break;       case '接待': $man = new Receiver;       break;       default: echo '传输参数有误,不属于任何一个职位';       break;   }

Connaught, this is the simple factory model, is not very common, the simple factory model has a shortage, although he followed the single principle of responsibility, but it violates another very important principle: open closure principle . If you add a clerk position, then we also have to modify the corresponding code, add a case, which is very scary, because the written code if we re-modify may cause an unknown effect.

The factory model is an upgrade to a simple factory, which is explained by the DB Class in MVC, when external calls simply choose the name of the table you want, the factory will call the real database processing method, and then return the results you want.

Whether it's Factory mode or other creation mode, it's a goal--to initialize an object. Or, to build a data structure model (classes and objects themselves are a custom data structure).

So, the question is, why is there a new way to create an object and use design patterns. Essentially, it's a reason not to let upper-level users initialize objects directly using new.

There are a number of reasons for this, most of which are the process of isolating objects created by the user of the upper layer, or whether the process of creating objects is complex, the user is not easy to master , or whether the object is created to meet certain conditions , which are required by the business. , is the system constraints or, there is no need for the upper-level users to master, increase the difficulty of others development.

So, at this point we should be clear, whether it is the factory model, or the above-mentioned closed-door principle, are to isolate a number of complex processes, so that these complex processes do not expose, if exposed to these processes, will add trouble to users, which is called teamwork.

Object-oriented encapsulation itself is designed to make the external API as simple as possible.

For example, you define a Status field, but this field requires an integer to represent the state for some business reason. Then, if the number is less good to do, if the number is more, the upper-level users will not necessarily be able to remember the status of each number represented (such as you want to do voice communication system, then, the voice device has a lot of status numbers). At this point, if you use new to create an object and then assign it, it is Status unavoidable that you might want to consult the development documentation, or you might accidentally give a wrong value. At this point, you may want to use the factory model, or other appropriate design patterns, to build the code.

For example, this:

public static class Factory{    public static Ixxxxxx CreateWithOpen()    {        var obj = new Obj();        obj.Status = 1;        return obj;    }    public static Ixxxxxx CreateWithClose()    {        var obj = new Obj();        obj.Status = 2;        return obj;    }}

Of course, the use of enumerations is also OK, this plainly, is to look at the designer's wishes.

Therefore, the design pattern does not say which scene must be used, or, more specifically, when you use the design pattern, can be convenient for your team members, or improve the quality of the code, to avoid some errors. If it is, use it, if it only brings complexity, and there is no benefit, then forget it.

In a word, no should not be used, there is no need to use, use will bring benefits, whether it is the team or product quality or maintainability of the product. Use not, to teamwork and product-oriented, this is the basic requirements of a software designer.

The function of the factory is that you give it a model or a specific sample requirement, it gives you a finished product. Factory mode is also such a reason, for example, you enter the parameter is a, it gives you a object, you enter the B, it will give you a B object, here, a, a, you let the factory production of goods specific needs, such as the length and width of high.

The factory model is still very common, and you may not be able to use it because the project is small or the class is not abstract.

Factory you can understand to hide the internal details, you call the factory production API, directly get the description of the object, specifically how to produce, you do not have to pay attention to the details, because some things simple, directly new out can be, but some very complex, such as the spring injection chain. To understand the factory model, it is recommended to look at the factory implemented by spring.

  • 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.