Detailed description of the use of the factory method mode in the design mode in the Python program, the design mode python

Source: Internet
Author: User

Detailed description of the use of the factory method mode in the design mode in the Python program, the design mode python

The Factory Method mode is also called the Virtual Constructor mode or the Polymorphic Factory mode, which belongs to the Creation Mode of the class. In the factory method mode, the parent class is responsible for defining the public interfaces for creating objects, while the Child class is responsible for generating specific objects, the purpose is to delay the class instantiation operation to the subclass, that is, the subclass determines which class should be materialized.
In simple factory mode, a factory class is at the center of product class instantiation. It knows the details of each product class and determines when a product class should be instantiated. The advantage of the simple factory mode is that the client can be independent from the product creation process, and there is no need to modify the client when introducing new products to the system. The disadvantage is that when a new product is to be added to the system, the factory class must be modified to add the necessary processing logic. The fatal weakness of the simple factory model is the factory class in the core position, because once it cannot determine which class to instantiate, it cannot be used, the factory method mode can effectively avoid this problem.
Consider an application Framework that can be used to browse documents in various formats, such as TXT, DOC, PDF, and HTML, in order to make the software architecture as generic as possible, the abstract parent classes "Application" and "Document" are defined at the design stage. The customer must use their subclass to process a specific type of documents. For example, to use this framework to compile a PDF file browser, you must first define two classes, namely Application and Document, which should inherit from Application and Document.
Application is responsible for managing documents and creating them as needed. For example, when you select Open or New from the menu, Application is responsible for creating an Document instance. Obviously, the specific Document subclass to be instantiated is related to a specific Application, so the Application cannot predict which Document subclass will be instantiated, and it only knows When a new Document (When) is created, but does not know Which (Which) specific Document will be created. If you still stick to the simple factory mode, there will be a very embarrassing situation: the framework must instantiate the class, but it only knows the abstract class that cannot be instantiated.
The solution is to use the factory method mode, which encapsulates the information to be created by the Document subclass and can separate the information from the framework. 1. The subclass of Application redefined the abstract method createDocument () of Application and returned an instance of an appropriate Document subclass. CreateDocument () is a factory method because it vividly describes the class instantiation process, that is, it is responsible for "producing" an object.

To put it simply, the function of the factory method mode is to generate various types of instances based on different conditions. These instances generally belong to multiple similar types and share a common parent class. The factory method mode encapsulates the creation process of these instances, which simplifies the compilation of customer programs and improves the scalability of the software architecture, this allows you to add new child classes at minimal cost in the future. The factory method is applicable to the following scenarios:
When you cannot know which class the object to be created belongs to or which class the object will be returned, the premise is that these objects comply with certain interface standards.
When a class wants its subclass to determine the object to be created, its purpose is to make the program more scalable and more flexible when it is added to other classes.
When the role of creating an object is delegated to one of the multiple help sub-classes (helper subclass), and you want to localize the information of which sub-classes are proxies.
It should be noted that using the factory method mode to create an object does not necessarily make the code shorter (in fact, it is often longer), and more auxiliary classes may need to be designed, however, it can indeed flexibly and elastically create unconfirmed objects, which simplifies the logic structure of the client application and improves the readability and reusability of the Code.

Take an animal factory as an Example

Class Animal (object): def eat (self, food): raise NotImplementedError () class Dog (Animal): def eat (self, food): print 'Dog ', foodclass Cat (Animal): def eat (self, food): print 'cat food', foodclass AnimalFactory (object): def create_animal (self): raise NotImplementedError () class DogFactory (Animal): def create_animal (self): return Dog () class CatFactory (AnimalFactory): def create_animal (self): return Cat () def client (): animal_factory = DogFactory () animal = animal_factory.create_animal () animal. eat ('meat bone') animal_factory = CatFactory () animal = animal_factory.create_animal () animal. eat ('fishbone ')

The following is the implementation of the simple factory model:

Class Animal (object): def eat (self, food): raise NotImplementedError () class Dog (Animal): def eat (self, food): print 'Dog ', foodclass Cat (Animal): def eat (self, food): print 'cat food', fooddef create_animal (name): if name = 'Dog': return dog () elif name = 'cat': return cat () def client (): animal = create_animal ('dog ') animal. eat ('meat bone') animal = create_animal ('cat') animal. eat ('fishbone ')

It seems that the factory method model is much more complicated than the simple factory model. Why should we use the factory method? The advantages of the simple factory mode are obvious. Factory functions encapsulate logic judgment, and the client is much less costly to use. The problem is also obvious. To add a new product type, you need to modify the factory function, which violates the open and closed principle. However, the Factory method pattern seems to have circled and returned to the original era. Is it okay to write it below? Why should we set up a Factory on the outside:

Class Animal (object): def eat (self, food): raise NotImplementedError () class Dog (Animal): def eat (self, food): print 'Dog ', foodclass Cat (Animal): def eat (self, food): print 'cat food', fooddef client (): dog = Dog () dog. eat ('bone') cat = Cat () cat. eat ('fishbone ')

The factory method mode is advantageous for languages that require strong type checks, such as Java and C ++, in code organization. For a dynamic language like Python, it doesn't feel much value. Maybe I haven't understood the true meaning of the factory method model.

Articles you may be interested in:
  • Measure the test taker's knowledge about the observer mode and Strategy Mode in Python Design Mode Programming.
  • Simple program example of interpreter mode in Python Design Mode Programming
  • An example of how to use the design pattern in Python
  • Analysis of the key points of the Decorator pattern in Python
  • Instance parsing Python Design Mode Programming-Application of Bridge Mode
  • Examples of Adapter mode in Python Design Mode Programming
  • Application Example of prototype in design mode in Python Program
  • In-depth analysis of the use of builder mode in Python Design Mode Programming
  • An example of how to use the abstract factory mode in Python Design Mode Programming
  • The example explains how to use the factory method mode of programming in Python design mode.
  • Use the simple factory mode for Python Design Mode Programming
  • Example of using the responsibility chain mode and iterator mode in the design mode in Python

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.