Talk about the role of the factory

Source: Internet
Author: User

"Reprint" Create object and use Object--talk about the function of factory

In the teaching and promotion of design patterns, many business students and students in the school often ask me what is the use of Factory mode (including simple Factory mode, factory method mode and abstract Factory mode), and many times it is possible to create objects flexibly by reflection mechanism. , in this article I'll talk about the role of the factory around creating objects and using objects.

The responsibilities associated with an object typically have three categories: the responsibility of the object itself, the responsibility to create the object, and the responsibility to use the object . The responsibility of the object itself is relatively easy to understand, which is the data and behavior of the object itself, which can be realized through some public methods. In this article, we will briefly discuss the object's creation responsibilities and usage responsibilities.

In the Java language, we typically have the following kinds of ways to create objects:

(1) Create objects directly using the new keyword;

(2) Creating objects by reflection mechanism;

(3) Creating objects through the Clone () method;

(4) Create objects from the factory class.

There is no doubt that using the new keyword directly in client code is the simplest way to create an object, but it is less flexible and is illustrated by a simple example:

[Java]View PlainCopy 
  1. Class Loginaction {
  2. private Userdao Udao;
  3. Public loginaction () {
  4. Udao = new Jdbcuserdao (); //Create Objects
  5. }
  6. public Void execute () {
  7. //other code
  8. Udao.finduserbyid (); //Use objects
  9. //other code
  10. }
  11. }

An object Udao of type Userdao is defined in the Loginaction class, a Jdbcuserdao object of type Udao is created in the Loginaction constructor, and the Execute () Method calls the Finduserbyid () method of the Udao object, and this code does not appear to be a problem. Let's analyze the relationship between Loginaction and Userdao, Loginaction class is responsible for creating an object of Userdao subclass and using Userdao method to complete the corresponding business processing. That is, Loginaction is responsible for the creation of Udao and is responsible for the use of Udao, the creation of objects and the use of the object's responsibilities coupled together, This design can lead to a serious problem: if you want to be able to use another subclass of Userdao such as Hibernateuserdao type object in Loginaction, you must modify the source code of the Loginaction class, violating the "open and closed principle". How do I fix the problem?

One of the most common workarounds is to remove the creation responsibility of the Udao object from the Loginaction class and create the object outside of the Loginaction class, so who is responsible for creating the Userdao object? The answer is: Factory class. By introducing a factory class, a customer class (such as Loginaction) does not involve the creation of objects, nor does the creator of the object involve the use of objects. The introduction of the factory class Userdaofactory is shown in structure 1:

Figure 1 Structure diagram after introduction of factory class

The introduction of the factory class will reduce the maintenance effort caused by changes in the product or plant class. If the constructor of one of Userdao's subclasses changes or if you want to add or remove different subclasses, just maintain userdaofactory code without affecting loginaction, if the Userdao interface changes, such as adding, Remove the method or change the method name, only need to modify the loginaction, will not give userdaofactory any impact.

In all the factory models, we emphasize that the relationship between two classes A and B should be just a to create B or a to use B, not two relationships . Separating the creation and use of objects also makes the system more consistent with the "single Responsibility Principle", which facilitates the reuse of functions and the maintenance of the system.

In addition, there is an advantage in separating the creation and use of objects: preventing data and code that is used to instantiate a class everywhere in multiple classes, the knowledge about creation can be moved to a factory class , in Joshua Kerievsky's "refactoring and Patterns" There is a special section in the book to introduce. Because sometimes we create an object not simply to call its constructor, but also to set some parameters, may also need to configure the environment, if the code is scattered in the client class of each created object, there is bound to be code duplication, create the spread of the problem, These customer classes do not have to take on the creation of objects, they simply use the created objects. At this point, you can introduce factory classes to encapsulate the creation logic of objects and instantiation/configuration options for client code.

There is a "not particularly obvious" advantage of using the factory class, a class may have multiple constructors, and in Java, C # and other languages the constructor name is the same as the class name, and the client can only invoke different constructors to create the object by passing in different parameters. From the constructors and argument lists, you may not understand the differences in the products constructed by the different constructors at all. But if you encapsulate the object creation process in a factory class, we can provide a series of factory methods that have a completely different name, each of which corresponds to a constructor , and the client can create objects in a more readable and understandable way, and Choosing a well-defined factory method from a set of factory methods is much more convenient than selecting a constructor from a different set of constructors with the same name parameter. 2 is shown below:

In Figure 2, the rectangular factory class Rectanglefactory provides two factory methods Createrectangle () and Createsquare (), one for creating rectangles, one for creating squares, These two methods are more explicit than directly using constructors to create rectangular or square objects, and to some extent reduce the probability of an error in client invocation.

So, one might ask, is it necessary to have a factory class for every class in the design? The answer is: specific analysis of the situation. If the product class is simple, and there are not too many variables, the construction process is very simple, it is not necessary to provide a factory class, directly before the use of the instantiation, such as the Java language of the string class, we do not need to provide it with a special stringfactory, This is a bit like overkill, overqualified, and will cause the factory flooding, increase the complexity of the system.

Talk about the role of the factory

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.