Factory Method

xiaoxiao2021-03-06  42

First, introduction

Factory Method mode is also known as a virtual constructor mode or polymorphic factory mode, which belongs to the class's creation mode. In the factory method mode, the parent class is responsible for defining the public interface of the creation of an object, and the subclass is responsible for generating a specific object, the purpose is to delay the instantiation operation of the class into the subclass, that is, subtypes to determine Which class should be physically solidified.

In simple factory mode, a factory class is in a central location of the product class, which knows the details of each product class and decide which product class should be instantiated. The advantage of simple factory model is to enable the client independently of the creation process of the product, and there is no need to modify the client when introducing new products in the system. The disadvantage is that when there is a new product to be added to the system, the factory class must be performed. Modify to add the necessary processing logic. The fatal weakness of simple factory model is a factory class in the core, because once it is unable to determine which class is instantiated, it cannot be used, and the factory method model can avoid this problem.

Consider such an application framework (which can be used to browse the documents in various formats, such as TXT, DOC, PDF, HTML, etc. These two abstract parent classes, customers must handle a specific type of document through their subclasses. For example, if you want to use the framework to write a PDF file browser, you must first define both classes of PDFApplication and PDFDocument, which should be inherited in Application and Document, respectively.

Application's responsibilities are managed for Document and create them when needed. For example, when the user selects Open or New from the menu, Application is responsible for creating an instance of a document. Obviously, the instantiated specific document subclass is related to the specific application, so Application cannot predict which document subclass will be instantiated, it only knows a new Document when it is created, but I don't know Which (Which) specific document will be created. At this point, if you still adhere to the use of simple factory models, a very embarrassing situation will appear: The frame must be instantiated, but it only knows the abstract class that cannot be instantiated.

The solution is to use the factory method mode, which encapsulates which Document subclass will be created, and can separate this information from the frame. As shown in Figure 1, the subclats of Application redefine the abstract method CREATEDOCUMENT () of the Application and returns an instance of an appropriate document subclass. We said that createDocument () is a factory method because it describes the instantiation process of the class very much, which is responsible for "production" an object.

figure 1

Simply put, the role of factory method model is to generate various types of examples depending on different conditions, which are usually a similar type and have a common parent class. Factory Mode Mode encapsulates these instances of the creation process, simplifies the writing of client programs, and improves the scalability of software architectures, making the new subclass with minimal expenses. Factory Method This mode is suitable for use in the following occasions:

When it is not known which class that must be created, or if it is not known which class that belongs to which class belongs will be returned, the premise is that these objects meet certain interface criteria. When a class wants to determine the object created by its subclass, its purpose is to make the program's scalability, more flexible when adding other classes. When creating the responsibility of the object is delegated to a plurality of helper subclass, it is desirable to be the information of the agent. It should be noted that the use of factory method mode is not meant to make code shorter (often longer), and may need to design more assisted classes, but it is indeed flexible, flexible Create an undetermined object, simplify the logical structure of the client application, and improve the readability and reusability of the code.

Second, the model introduction

Factory Method This mode is not complicated, but it is one of the most important design patterns. Whether in COM, CORBA or EJB, you can see it everywhere. A basic idea of ​​object-oriented is reasonable allocation between different objects, in essence, factory method mode is a polymorphic method for creating objects, which declares in abstract parent classes The method interface used to create an object, and the specific subclass will locate the object's creation process by overwriting the method, including whether or not, whether it is initialized, and the like. From a certain extent, the factory method can be seen as a specialization of the constructor, and the particularity is manifested in creating different objects with a consistent way, without worrying about which class is currently instantiating, because it is created Which class object will depend on its subclass.

Suppose we intend to develop software for Personal Information Manager, PIM, which saves the various information needed in daily work and life, including address book, phone book, date reminder, schedule, etc. Obviously, the design of the PIM user interface will be more complicated because the input, verification, and modifications of each information must be provided separate interfaces to interact with the user. A relatively simple approach is to write the corresponding user interface for the processing of various information in the PIM, but the cost will result in very poor scalability of the software, because once the function is administered to other information (such as bank accounts) When it is necessary to modify the PIM, add the corresponding user interface, so that PIM will eventually become more complex, the structure is large and difficult to maintain. The improvement method is to separate the user interface of various information from the PIM, so that the PIM no longer cares about how the user enters data, how to verify the user input, and how the user modifies information, all of which are parallel The software module is completed, while PIM is only available to provide an overall framework for management of these personal information.

A universal interface editable can be designed for specific implementation, and all user interfaces that processes specific personal information (such as communication addresses and phone numbers) are inherited in it, and PIM obtains an instance of Editor by EDITABLE. And use it to make a unified process of user input. For example, after the user completes the input, the PIM can call the method getContent () in Editor to obtain the data input by the user, or call the resetUi () to clear the data input by the user. After using this architecture, if you want to expand the functionality of the PIM, simply add the corresponding editable and editor, without modifying the PIM itself.

There is another step away from the target, because Editable and Editor are just a universal interface, but PIM needs to instantiate their subclasses. At this time, it should naturally want to use the factory method mode, define an EditableFactory interface for PIM to create Editable object. In this way, the architecture of the entire PIM will be shown in Figure 2. figure 2

The Editable interface defines a public constructive method () getEteditor (), which returns an Editor object, and its complete code is shown in Listing 1. Any personal information has its own independent user interface (editor), responsible for obtaining data and modifying when needed, and PIM only wants to get Editor through Editable, and use it to enter the data input to the user Perform a corresponding operation.

Code List 1: Editable.py

Class Editable:

"" "" "Personal Information User Interface" ""

# Get your personal information editing interface

Def getEteditor (Self):

PASS

The Editor interface gives a common interface that handles all personal information, which is shown in Listing 2. PIM can obtain a UI component that interacts with the user by calling the GetUI () method. These components may be simple to just a text input box according to the personal information currently being processed, and can be complicated to be a plurality of graphics controls. (Widget) dialog. With the getContent (), Commitchanges (), and resetui () methods provided by Editor, PIM can also get, submit or empty the personal information entered by the user. After introducing Editor, PIM can be freed from the user interface that handles a particular personal information, so that the attention can be intended to manage the information on how to manage this information.

Code List 2: editor.py

Class Editor:

"" "Users use specific Editor to edit personal information" ""

# Get objects on behalf of the user interface (UI)

Def getui (Self):

PASS

# Get the data entered by the user

DEF getContent (Self):

PASS

# Submit the data entered by the user

Def Commitchanges (Self):

PASS

# # Clear user input data

Def Resetui (Self):

PASS

EditableAddress is a concrete implementation of Editable, and PIM uses it to handle personal address information, and its complete code is shown in Listing 3.

Code List 3: EditableAddress.py

From Editor Import Editor

From Editable Import Editable

Import tkinter

Class EditableAddress (Editable):

"" "" "" "" "" "For handling personal address information" ""

# Constructor

DEF __INIT __ (Self, MASTER):

Self.master = Master

Self.name = "" "

Self.Province = ""

Self.city = "" "

Self.Street = ""

Self.zipcode = "" "

Self.EDitor = addresseditor (Self)

# Get the associated editor

Def getEteditor (Self):

Return Self.editorClass Addresseditor (Editor, Tkinter.frame):

"" "Editor" "" "" "" ""

# Constructor

DEF __INIT __ (Self, Owner):

Tkinter.frame .__ init__ (self, ooner.master)

Self.Owner = Owner

Self.name = tkinter.stringvar ()

Self.Province = tkinter.stringvar ()

Self.city = tkinter.stringvar ()

Self.Street = tkinter.stringvar ()

Self.zipcode = tkinter.stringvar ()

Self.createWidgets ()

# Construct the user interface

DEF CREATEWIDGETS (Self):

# 名

Nameframe = tkinter.frame (Self)

Namelabel = tkinter.label (nameframe, text = "Name:")

NameEntry = Tkinter.Entry (nameframe, TextVariable = self.name)

Namelabel.config (anchor = tkinter.e, width = 8, pady = 3)

Namelabel.pack (Side = tkinter.Left)

NameEntry.Pack (Side = tkinter.Left)

Nameframe.pack ()

# 省 省

Provinceframe = tkinter.frame (Self)

ProvinceLabel = tkinter.label (provinceframe, text = "province:")

ProvinceEntry = tkinter.Entry (provinceframe, textvariable = self.province)

ProVinceLabel.config (Anchor = tkinter.e, width = 8, Pady = 3)

ProvincialLabel.pack (Side = tkinter.Left)

ProvinceEntry.Pack (Side = tkinter.Left)

provinceframe.pack ()

# city

Cityframe = tkinter.frame (Self)

CityLabel = tkinter.label (Cityframe, Text = "City:")

CityEntry = Tkinter.Entry (Cityframe, TextVariable = Self.city)

Citylabel.config (Anchor = tkinter.e, width = 8, Pady = 3)

CityLabel.pack (Side = tkinter.Left)

CityEntry.Pack (Side = tkinter.Left)

Cityframe.pack ()

#

Streetframe = tkinter.frame (Self)

StreetLabel = tkinter.label (StreetFrame, Text = "Street:")

stretentry = tkinter.Entry (StreetFrame, TextVariable = Self.Street)

StreetLabel.config (Anchor = tkinter.e, width = 8, pady = 3) streetlabel.pack (Side = tkinter.Left)

Streetntry.pack (Side = tkinter.Left)

streetframe.pack ()

# 邮编

Zipcodeframe = tkinter.frame (Self)

ZipcodeLabel = tkinter.label (zipcodeframe, Text = "ZIP Code:")

ZipcodeEntry = tkinter.Entry (Zipcodeframe, TextVariable = Self.zipcode)

ZipcodeLabel.config (Anchor = tkinter.e, width = 8, pady = 3)

ZipcodeLabel.pack (Side = tkinter.Left)

ZipcodeEntry.Pack (Side = tkinter.Left)

Zipcodeframe.PACK ()

# 重载 的 的 的 的 的 的 的 的 对,

Def getui (Self):

Return Self

# 重载 的 的 的 的 的 的 的 的 数据,

DEF getContent (Self):

Content = "Name:" Self.name.get () "/ n"

Content = "province:" Self.Province.get () "/ n"

Content = "City:" Self.city.get () "/ n"

Content = "street:" Self.Street.get () "/ n"

Content = "Zip code:" self.zipcode.get ()

Return Content

# 重载 的 的 的 的 的 的 的 的 数据,

Def Commitchanges (Self):

Self.owner.name = self.name.get ()

Self.owner.province = self.province.get ()

Self.owner.city = self.city.get ()

Self.Owner.Street = Self.Street.get ()

Self.Owner.zipcode = self.zipcode.get ()

# 重载 的 的 的 的 的 的 的 e,

Def Resetui (Self):

Self.name.set ("")

Self.Province.Set ("")

Self.city.set ("")

Self.Street.Set ("")

Self.zipcode.set ("")

EditablePhone is another specific implementation of Editable, and PIM uses it to handle your personal phone number, and its complete code is shown in Listing 4.

Code List 4: EditablePhone.py

From Editor Import Editor

From Editable Import Editable

Import tkinter

Class EditablePhone (Editable): "" "" "" "" "" "" "

# Constructor

DEF __INIT __ (Self, MASTER):

Self.master = Master

Self.areAcode = ""

Self.phonenumber = "" "

Self.EDitor = PhoneEditor (Self)

# Get the associated editor

Def getEteditor (Self):

Return Self.EDitor

Class PhoneEditor (Editor, Tkinter.frame):

"" "Editor" "" "" "" "

# Constructor

DEF __INIT __ (Self, Owner):

Self.Owner = Owner

Tkinter.frame .__ init __ (self, self.owner.master)

Self.areAcode = tkinter.stringvar ()

Self.phonenumber = tkinter.stringvar ()

# Construct the user interface

Codelabel = tkinter.label (self, text = "Area code:")

CodeEntry = tkinter.Entry (self, textvariable = self.areacode)

Codelabel.config (anchor = tkinter.e, width = 12, pady = 3)

Codelabel.grid (row = 0, column = 0)

CodeEntry.grid (row = 0, color = 1)

Numberlabel = tkinter.label (self, text = "Phone Number:")

NumBerentry = tkinter.Entry (self, textvariable = self.phonenumber)

Numberlabel.config (anchor = tkinter.e, width = 12, pady = 3)

Numberlabel.grid (row = 1, colorn = 0)

NumberenTry.grid (Row = 1, Column = 1)

# 重载 的 的 的 的 的 的 的 的 对,

Def getui (Self):

Return Self

# 重载 的 的 的 的 的 的 的 的 数据,

DEF getContent (Self):

Content = "Area Code:" Self.areAracode.get () "/ n"

Content = "Phone Number:" Self.phonenumber.get () "/ n"

Return Content

# 重载 的 的 的 的 的 的 的 的 数据,

Def Commitchanges (Self):

Self.Owner.areAcode = self.areacode.get ()

Self.owner.phonenumber = self.phonenumber.get ()

# 重载 的 的 的 的 的 的 的 e,

Def Resetui (Self):

Self.areAracode.Set (") Self.phonenumber.set (" ")

The EditableFactory interface is the core of applying factory method mode in PIM, and its complete code is shown in Listing 5. Unlike the "Super Class" of all objects in the simple factory model, EditableFactory only defines how to instantiate Editable's factory methods CreateEditable (), do not master their livelihood, truly responsible for completing the creation of workfactory class.

Code List 5: EditableFactory.py

Class EditableFactory:

"" "Used to create an editable factory" ""

# Instantiate Editable objects

DEF CREATEEDITABLE (Self, Master):

PASS

EditableAddressFactory is a concrete implementation of EditableFactory, and PIM uses it to instantiate EditableAddress objects, and its complete code is shown in Listing 6.

Code List 6: EditableAddressFactory.py

From EditableFactory Import EditableFactory

From EditableAddress Import EditableAddress

Class EditableAddressFactory (EditableFactory):

"" "Used to create an inditableaddress factory class" ""

# 重载 的 的 的 的 的 方法,

DEF CREATEEDITABLE (Self, Master):

Address = EditableAddress (Master)

Return Address

EditablePhoneFactory is another specific implementation of EditableFactory, and PIM uses it to instantiate the EditablePhone object, and its complete code is shown in Listing 7.

Code List 7: EditablePhoneFactory.py

From EditableFactory Import EditableFactory

From EditablePhone Import EditablePhone

Class EditablePhoneFactory (EditableFactory):

"" "Used to create an inditablephone factory" ""

# 重载 的 的 的 的 e,

DEF CREATEEDITABLE (Self, Master):

Phone = EditablePhone (Master)

Return Phone

After all of these auxiliary classes are defined, the PIM class can be written later, which provides a framework for all personal information, and its complete code is shown in Listing 8.

Code List 8: Pim.py

From EditablePhone Import EditablePhone

From EditableAddressFactory Import EditableAddressFactory

From EditablePhoneFactory Import EditablePhoneFactory

Import tkinter

Class Pim:

"" Personal Information Management "" "

# Constructor

DEF __INIT __ (Self):

Mainframe = tkinter.frame () mainframe.master.title ("pim")

# 按钮

AddressButton = tkinter.button (mainframe, width = 10, Text = "address")

PhoneButton = tkinter.button (mainframe, width = 10, text = "phone")

Commitbutton = tkinter.button (mainframe, width = 10, Text = "commit")

RESETBUTTON = tkinter.button (mainframe, width = 10, text = "reset")

AddressButton.config (Command = Self.AddressClick)

PhoneButton.config (Command = Self.PhoneClicked)

Commitbutton.config (Command = Self.commitclicKed)

ResetButton.config (Command = self.resetclicked)

AddressButton.Grid (Row = 0, Column = 1, PADX = 10, Pady = 5, Stick = Tkinter.e)

PhoneButton.grid (row = 1, column = 1, padx = 10, pady = 5, stick = tkinter.e)

CommitButton.grid (row = 2, column = 1, padx = 10, pady = 5, stick = tkinter.e)

RESETBUTTON.GRID (ROW = 3, Column = 1, PADX = 10, Pady = 5, Stick = Tkinter.e)

# Containers used to accommodate all kinds of editor

Self.editorFrame = tkinter.frame (Mainframe)

Self.editorframe.grid (ROW = 0, Column = 0, ROWSPAN = 4)

Self.editorFrame.grid_configure (stick = tkinter.n, pady = 15)

Self.EDitor = tkinter.frame (self.editorframe)

Self.editor.grid ()

# Personal Information Display Area

Self.content = tkinter.stringvar ()

Self.ContentLabel = Tkinter.Label (mainframe, width = 50, height = 5)

Self.ContentLabel.configure (TextVariable = Self.content)

Self.ContentLabel.configure (Anchor = tkinter.w, font = "arial 10 italic bold")

Self.ContentLabel.configure (relief = tkinter.ridge, pady = 5, padx = 10)

Self.ContentLabel.grid (Row = 4, Column = 0, ColumnSpan = 2)

Mainframe.pack ()

Mainframe.mainloop ()

# Address button callback function

Def addressclicked (self): address = editableaddressFactory (). CreateEditable (Self.editorFrame)

Self.EDitor.grid_remove ()

Self.EDitor = address.GetEteditor ()

Self.editor.getui (). Grid ()

# Phone button callback function

Def phoneclicked (Self):

Phone = editablephonefactory (). CreateEditable (Self.EDitorFrame)

Self.EDitor.grid_remove ()

Self.EDitor = phone.GetEteditor ()

Self.editor.getui (). Grid ()

#Sso callback function

Def Commitclicked (Self):

Content = self.editor.getContent ()

Self.content.set (Content)

# RESET button callback function

Def ResetClicked (Self):

Self.editor.Rsetui ()

# 主 函函

IF (__name__ == "__main__"):

App = Pim ()

Figure 3 is an interface effect of PIM at runtime.

image 3

Third, general structure

The factory method model is a further abstract and promotion of simple factory model. It not only maintains the advantages of the simple factory model to hide the class of the class, but also overcome the factory class too complicated and is not easy to expand through polymorphism. Disadvantages. In the factory method mode, factory classes in the core are no longer responsible for the creation of all products, but to complete the specific creation work. After the functional abstraction, the core factory class has become an abstract factory role, which is only responsible for the interface that must be implemented by the specific factory subclass, without involving which product class should be instantiated. The general structure of the factory method mode is shown in Figure 4, in the figure, for simplification, only one product class and a factory class are given, but multiple product classes and multiple factory classes are often designed in actual systems.

Figure 4

The essence of the factory method model is to delay the creation of the object to its subclass, that is, the subclasses determine which product class should be instantiated according to the current situation. As can be seen from the above figure, the factory method model involves four participants in abstract factory roles, specific factory roles, abstract product roles and specific product roles.

Abstract Factory Role is the core of factory method model, which is responsible for defining a factory approach to creating abstract product objects. Abstract plants cannot be called directly by the outside, but any factory class that is used to create a product object in the mode must implement the factory method defined by it. Concrete Creator Role is an external interface of factory method mode, which is responsible for implementing internal logic of creating specific product objects. Specific factories are closely related to applications, can be called directly by the outside world, create the products required. Abstract Product Role is the parent class of all objects created by the factory method mode, which is responsible for describing public interfaces with all specific products. The Concrete Product Role is an instance of a specific class that acts as a particular class that acts as this role.

Abstract factory roles are responsible for declaring factory method (manufactured "to" production "abstract products, the following is an exemplary Python code of abstract factories:

Code List 9: Creator.py

Class Creator:

"" Abstract factory role "" "

# Creating a factory method for abstract products

DEF FACTOREMETHOD (SELF): Pass

The specific factory role is responsible for creating an instance of a specific product and returns it to the caller. The specific factories are related to specific products, and the general common practice is to define a specific factory for each specific product. The following is an exemplary Python code for a specific plant:

Code List 10: Concretecreator.py

Class Concretecreator (CREATOR):

"" "Specific Factory Role" ""

# Creating a factory method for specific products

DEF FACTORYMETHOD (SELF):

Product = concreteproduct ()

Return Product

The main purpose of abstract product roles is to provide a common interface for all specific products, usually just give a corresponding statement, without giving a specific implementation. The following is an exemplary Python code for abstract product classes:

Code List 11: Product.py

Class Product:

"" Abstract product role "" "

# All product class public interface

DEF Interface (Self):

PASS

The specific product role acts as a final creation goal. It is generally a subclass of abstract product classes that realizes all factory methods defined in an abstract product class. When actual applications, it is usually complicated. The following is an exemplary Python code for the specific product class:

Code List 12: ConcreteProduct.py

Class ConcreteProduct (Product):

"" "Specific product role" ""

# 公 接 接 实 实 实

DEF Interface (Self):

Print "Concrete Product Meduct Method"

When using factory method mode, it is often necessary to introduce a client role, which is responsible for creating a specific factory object, and then calls factory methods in the factory object to create the corresponding product object. The following is an exemplary Python code of the client:

Code List 13: Client.py

Class Client:

"" "Client role" ""

DEF RUN (Self):

Creator = concretecreator ()

Product = creator.FactoryMethod ()

Product.INTERFACE ()

# 主 函函

IF (__name__ == "__main__"):

Client = client ()

Client.run ()

In this simple schematic implementation, there is only one class that acts as a specific product and specific factory role, but in real practical applications, there is usually a number of specific product classes at the same time. Multiple specific factory classes are required, each of which is responsible for the production of specific products.

Factory Mode Mode Activity Sequence As shown in Figure 5, the client client first creates a ConcreteCreator object, then calls the factory method of the ConcreteCreator object () FactoryMethod (), which is responsible for the "production" CONCRETEPRODUCT object.

Figure 5

Fourth, actual use

Using factory method models can introduce new products without modifying specific factory roles, this undoubtedly makes the factory method model better scalability than simple factory models. When developing the actual software system, it is usually designed to design the product role before starting to design the plant role, and complex demand results in a very large tree structure that will form a very large tree between abstract products and specific products, as shown in Figure 6.

Figure 6

In the above product level structure, more than one abstract product class, and more than two class levels, which are often encountered in the constructive real system. When applies a factory method mode for this software architecture, the usual practice is to design an identical plant level structure according to the grade structure of the product, as shown in Figure 7. Figure 7

Defining the purpose of the factory role is to create a corresponding product role, so the architecture of the entire system will be shown in Figure 8. This structure is often referred to as parallel class hierarchies, which makes a class to delegate its responsibilities to another independent class, and the factory method is a link between the two. The factory method mode does not limit the number of layers of the product level, although only two levels (abstract product layer and specific product layer) given in the previously given, but often require more complex product levels when practical use.

Figure 8

In the general structure of the factory method mode, whenever the factory method in the specific factory class is requested, the constructor of the specific product class will be called to create a new product instance, and then provide this instance to the client. However, when applying factory method patterns in actual software systems, the fact that the factory method can make more complex, and one of these most commonly used the product object. The strategy used is to register all the product objects created by the factory object into an object pool, so whenever the customer requests a factory method to create a corresponding product object, you can query the eligible product object from the object pool. If there is such an object in the object pool, then the product object is returned to the client directly; if there is no such object in the object pool, create a new product object that meets the requirements, register it to the object pool. In, then return to the client.

The plant method model relies on the polymorphism of factory roles and product roles, but this mode may be degraded when practical use, and its performance is the loss of polymorphism. In the factory method mode, all specific factory objects should share an abstract superclass, or in other words, there should be multiple specific factory classes as a subclass of abstract factories, but if the factory level There is only one specific factory class in the structure, then the abstract factory role can be omitted. When the abstract factory role is omitted, the factory method mode has a degradation. This degradation is characterized by the loss of plant role polymorphism. After degeneration, the model can still play some factory method model, and is often referred to as degraded factories. Method mode. Degraded factory method model is largely similar to simple factory model, as shown in Figure 9, can consider replacing with simple factory mode when practical.

Figure 9

In the factory method mode, it should be an abstract product type, not the specific product type, because only this can guarantee the polymorphism of the product role. That is, the client of the calling factory method can be programmed for the abstract product class without having to rely on the specific product class. It may have a very special situation in actual use, that is, the factory method only needs to return a specific product class. At this time, the function of the factory method mode will degrade, but this degradation will be characterized by product role polymorphism. Loss of sex, as shown in Figure 10. Strictly speaking, when this degradation occurs when the plant method model occurs, it is no longer referred to as a factory method mode, because the client can judge what type of object to get from the factory method, and this is exactly Violation of the original intention of the factory method model.

Figure 10

Five, advantages and deficiencies

In the factory method mode, the factory method is used to create the products needed by the customer, while also hiding which specific product class will be instantiated. The core of the factory method model is an abstract factory class. A variety of specific factories have since inherited from the abstract factory category, making customers only care about the abstract product and abstract factory, which is completely unused to return which specific product Needless to care about how it is created by a specific factory. Polymorphism design based on factory roles and product roles is the key to factory method model, which makes the factory independently determines what product objects created, and how to create this object is completely encapsulated inside the specific plant. The reason why the factory method mode is also known as polymorphism factories, which is obviously because all specific factory classes have the same extraction parent class.

Another advantage of using the factory method model is that when adding new products in the system, there is no need to modify the interface provided by the abstract factory and abstract products, and as long as you add a specific factory and the specific product, it is not necessary to modify the client. There is no need to modify other specific factories and specific products, and the scalability of the system is very scalable. Excellent object-oriented design encourages the encapsulation and delegation to construct software systems, and factory method model is a typical example of encapsulation and commission, in which package is reflected by abstract factories, but the commission is Through the abstract factory, the responsibility of creating an object is completely handed over to specific factories.

The disadvantage of using the factory method mode is that when adding new products, it is necessary to write new specific product classes, and provide the specific factory class with corresponding to the two, and when both are simpler, the additional overhead of the system is relatively large.

Sixth, small knot

The core idea of ​​factory method model is to define a common interface used to create an object, which is used by the factory rather than a customer to determine the class that needs to be instantiated, which is usually used when constructing the overall framework. The factory method model seems to be relatively simple, but the connotation is extremely profound, abstract, package, inheritance, entrustment, polymorphism, etc., the theory of object-oriented design is very good, and the application range is very wide.

转载请注明原文地址:https://www.9cbs.com/read-52587.html

New Post(0)