Simple factory

xiaoxiao2021-03-06  48

Create mode

Creative pattern (Creational Pattern) abstracts the instantiation process of the class, enabling the software module to create unrelated and organizational independence. In order to make the architecture more clear, some software is designed to create a specific instance of the class, which can dynamically determine how to create objects, create which objects, and how to organize and represent these objects according to specific contexts, and how to organize and represent these objects. The mode is what to describe how to solve these problems.

Different by the generation target, the creation mode can be divided into two types of creation patterns and objects of the object:

The creation mode of the class's creation mode class is completed by using inheritance relationships, which is completed by the creation of the class, which hides how to get the details of the specific class, and how the instances of these classes are Create and organize together. The creation mode of the object's creation mode object is completed by delegate the object's creation to another object, which can dynamically determine which specific classes of the specific class according to the context, and how to hide these instances to the outside and how to create and How to organize the details.

All creation modes have two eternal main melody: First, they all use the specific classes of the system to encapsulate; second, they hide how these classes are created and organized. The outside world only knows their common interfaces without knowing its specific implementation details. Because of this, create what (WHO) created, and who (WHO) is created, and when creating these aspects, it has provided software designers as much flexibility.

Specific to Python, suppose there is such a class:

Class Person:

DEF __INIT __ (Self, Name):

SELF.NAME = Name

To create an instance of such a class, you should do the following statement:

P = Person ("gary")

However, if you have a very complex work when you create an object, you need a long code, you can't simply write all the __init__ method, because this will violate two basic principles for object-oriented ideas: package (Encapsulation ) And delegation. If you have to do something, the result will only make your code into a hard code, and the structure of the entire software is very likely to be very bad, because some other modules may be dependent. This instance you created, which increases the coupling between the modules between invisible.

Package the creation process of the Python object into a class to complete it separately, allowing your program more flexible and universal. Practice has proven that the following six creation modes can better improve the creation process of the object:

The Simple Factory mode specifically defines a class to be responsible for creating an instance of other classes, and the instance created is usually common parent class. Factory Method mode is done with a standard method of creating an object's creation of the parent class, rather than its constructor, what objects should be created by the specific subclass responsible for determining. The Abstract Factory mode provides a common interface to create multiple objects associated with each other. The Singleton mode ensures that the system will only generate an instance of this class, and is also responsible for providing a standard method for accessing the instance to the outside world. The Builder mode distinguishes the creation of complex objects to the specific expression of their specific performance, which can be obtained as needed. Prototype mode utilizes a class that can be copied to itself, making the object's dynamic creation easier.

Second, the model introduction

Simple factory mode is also known as static factory method mode, which belongs to the creation mode of the class. This model is based on the information given by the outside, "Manufacture" out of certain "Product" objects, all kinds of class objects can be processed, usually inherited in the same parent class, and to the outside world Provide basic identical interfaces, but it will be different in specific implementation.

Suppose we have to develop a drawing program to draw simple geometries, this software should be able to handle the following geometries:

Circle Rectangle Rhombus (Diamond)

In addition to their own unique properties and methods, all geometry can almost abstract two public methods of drawing (ORASE), so that they can define a common interface shape. Although the Python language itself does not support the interface, in order to better clarify the idea of ​​design patterns, sometimes we still borrow the concept of the interface in the UML. In this way, the relationship between the various classes will be shown in Figure 1:

figure 1

The Shape interface defines all geometric graphics to implement public methods: DRAW () and ERASE (), implementing the Python code of the interface as shown below, there is no interface in Python, so the class can be used in the specific implementation.

Code List 1: Shape.py

Class Shape:

# 图 图形

DEF DRAW (Self):

PASS

# 图 graphic

DEF ERASE (Self):

PASS

The Circle Class is a specific form of Shape that implements all methods defined by the Shape interface, and an attribute __radius is added to represent the radius of the circle. The following is the code that implements the Circle class:

Code List 2: Circle.py

Class Circle (Shape):

DEF __INIT __ (Self, Radius = 0):

Self .__ radius = radius

#

DEF DRAW (Self):

Print "Draw Circle"

#

DEF ERASE (Self):

Print "ERASE CIRCLE"

# # 半 取 值 方法

Def getradius (Self):

Return self .__ radius

# # 半 方法

Def setRadius (Self, Radius):

Self .__ radius = radius

The Rectangle class is also a specific form of Shape, which implements all methods defined by the Shape interface, and adds two properties of __width and __height, indicating the width and height of the rectangle. The following is the code that implements the Rectangle class:

Code List 3: Rectangle.py

Class Rectangle (Shape):

DEF __INIT __ (Self, Width = 0, Height = 0):

Self .__ width = width

Self .__ height = height

#Draw a rectangle

DEF DRAW (Self):

Print "DRAW Rectangle"

# Rectangle

DEF ERASE (Self):

Print "Erase Rectangle"

# # 取 取 method

DEF getWidth (Self):

Return self .__ width

# 方法 方法

Def setWidth: Self, Width:

Self .__ width = width

# 高度 值值 值

Def GetHeight (Self):

Return Self .__ height

# 高度 值 方法

Def setHeight (Self, Height):

Self .__ height = height

Similarly, the Diamond class is also a specific form of Shape, which implements all methods defined in the Shape interface, and adds the two properties of __width and __height, indicating the width and height of the rhombus. The following is the code for implementing the Diamond class:

Code List 4: Diamond.py

Class Diamond (Shape):

DEF __INIT __ (Self, Width = 0, Height = 0):

Self .__ width = width

Self .__ height = height

#Draw diamond

DEF DRAW (Self):

Print "DRAW Diamond"

#

DEF ERASE (Self):

Print "Erase Diamond"

# # 取 取 method

DEF getWidth (Self):

Return self .__ width

# 方法 方法

Def setWidth: Self, Width:

Self .__ width = width

# 高度 值值 值

Def GetHeight (Self):

Return Self .__ height

# 高度 值 方法

Def setHeight (Self, HEIGHT):

Self .__ height = height

All geometric graphics classes are defined, the following is to provide a "factory" class ShapeFactory to create specific instances of various geometric graphics. The role of the ShapeFactory class is to create different geometric graphics objects, such as circular, rectangle or diamond, in accordance with the requirements of the outside world, such as the architecture of the entire software will be shown in FIG.

figure 2

The ShapeFactory class is used to create an instance of various geometric graphics. In fact, the current code is as follows:

Code List 5: ShapeFactory.py

Class ShapeFactory:

DEF FACTORY (Self, Which):

if which == "circle":

Return circle ()

Elif Which == "Rectangle":

Return Rectangle ()

Elif Which == "Diamond":

Return Diamond ()

Else:

Return none

A method Factory () is defined in the ShapeFactory class, and the outside world is creating the geometric graphic object, but if the requested class is not supported by the system, NONE will be returned. After introducing the factory class, other modules want to generate an instance of the geometry class, simply call the Factory () method of the ShapeFactory class:

FAC = ShapeFactory ()

Shape = FAC.FACTORY ("Diamond")

IF shape! = none:

Shape.draw () Successfully interested this implementation detail of how the class is hidden to the outside, which is the basic strategy taken by simple factory model.

Third, general structure

Simple factory model belongs to the creation mode of the class, suitable for instantiating a large number of classes with a common interface, can it be postponed when running, and dynamically determines which class of instances to create, not when compiling, you must know Which class is instantiated. The general structure of simple factory model is shown in Figure 3:

image 3

The essence of simple factory model is based on incoming parameters based on incoming parameters, and the dynamic decision should create an instance of which product class. As can be seen from the figure, simple factory model involves three participants in factory roles, abstract product roles and specific product roles.

The Creator Role is the core of simple factory model, which is responsible for implementing internal logic of all instances. Factory class can be called directly to create the product objects required. Abstract Products The character is the parent class of all objects created by simple factory modes, which is responsible for describing the common interfaces commonred in all instances. The Concrete Product Role is a simple factory model creation goal, all created objects act as an instance of a specific class that is as this role.

The factory role is responsible for creating an instance of a specific product and returns it to the caller, the following is an exemplary Python code of the factory class:

Code List 6: Creat.py

Class Creator:

# Create a specific product class

DEF FACTORY (SELF):

Return ConcreteProduct ()

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 7: Product.py

Class Product:

# All specific product class public interface

DEF Interface (Self):

PASS

The specific product role acts as the ultimate creation goal, which is generally a subclass of an abstract product class, implements all interface methods defined in an abstract product class. The following is an exemplary Python code for the specific product class:

Code List 8: Concrete.py

Class ConcreteProduct (Product):

# 公 接 接 实 实 实

DEF Interface (Self):

Print "Concrete Product Meduct Method"

When using simple factory mode, you can use the following exemplary Python code:

FAC = CREATOR ()

P = fac.factory ()

IF P! = none:

p.interface ()

In this simple schematic implementation, there is only one class that acts as a specific product role, but in real practical applications, it is usually encountered to have multiple specific product classes.

Fourth, actual use

When using a simple factory model to develop a real software system, there may be a very complex tree structure between abstract products and specific products, as shown in Figure 4.

Figure 4

Although such structures do not meet all specific product classes in the basic principles of the same abstract product class, it is not difficult to find that all specific product classes are derived from the same abstract yield class, which encounters this situation. It is only a slight change, and it is still possible to use the same factory class to create an instance of all specific product classes, but the software structure at this time will be shown in Figure 5.

Figure 5

When the relationship between the abstract product and the specific product class makes complicated, a benefit of using a simple factory model is that the structural relationship between the various product classes is not reflected in the factory class, and their structural changes will not Affect the factory class. It is precisely because simple factory models are treated separately for various specific product classes, so factory classes do not need to figure out the structure relationship between them, but only what specific product classes can be instantiated and how It is possible. However, doing this sometimes produces some troubles, that is, when adding new specific product classes, inevitably leads to amendments to the factory class. If there is only one specific product class when using simple factory mode, in order to simplify the software architecture, you can consider streamlining simple factory models, omitting the role of abstract products. At this point, the structure of the simple factory model will be shown in Figure 6.

Figure 6

In simple factory mode, a class that acts as a factory role usually only has a method, which is used to create Factory (). In some special occasions, if you need it, you can consider that the function of the factory role is replaced by the abstract product role, and the structure of the simple factory mode will be shown in Figure 7.

Figure 7

In the more extreme case, the factory role, abstract product role and specific product role can be merged, and all functions will be uniformly completed. That is, the simple factory model will degenerate into a separate specific product class. This class is also its own factory, which is responsible for creating its own instance, as shown in Figure 8.

Figure 8

This degraded simple factory model is substantially equivalent to one class, the only difference is that the default constructor is no longer used in the initialization of the object, but uses a custom factory method, but this is in many cases Not very large, especially for Python's dynamic type language. Since the degraded mode does not take advantage of the characteristics of simple factory model, it is best to use it carefully, and of course, it can also be replaced with other modes.

Five, advantages and deficiencies

In simple factory mode, factory class is the key to the entire model. It contains the necessary judgment logic, which can determine which specific class object that should be created according to the information given by the outside world. By using the factory class, the outside world can get rid of the embarrassing situation of direct creating specific product objects, just only responsible for "consumption" object, without having to manage how these objects are created and how to organize, this is clear The respective responsibilities and power are conducive to the optimization of the entire software architecture.

However, all things are favorable, the shortcomings of simple factory models are also reflected in their factory. Since the factory class concentrates all instances of creation logic, it is an omnipotent "god class", so it is critical to the entire software system, and if this class does not work properly, other parts may be affected. Implicated, the so-called "City Gate Fire, Cell Fish".

There is also another shortcomings in a factory class, that is, when the specific product classes in the system are increasing, the factory class may have a demand for different instances according to different conditions, this pair condition Judging and judge the specific product type, it is difficult to avoid the spread of module functions, and it is also very disadvantageous to the system's expansion and maintenance.

These disadvantages of simple factory models, in the next time you want to have a certain degree of overcoming, well, good, next time!

Sixth, small knot

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

New Post(0)