The creational pattern abstracts the class instantiation process, so that the software module is unrelated to object creation and organization. To make the architecture clearer, some software design requires that when creating a specific instance of the class, you can dynamically decide how to create and what objects to create according to the specific context, and how to organize and represent these objects, and the Creation Mode must describe how to solve these problems.
Depending on the Generation target, the creation mode can be divided into the class creation mode and the object Creation Mode:
Class Creation Mode
The class creation mode uses an inheritance relationship to assign the class creation to a specific subclass, so that the implementation details of the specific class are hidden from the outside world, and how the instances of these classes are created and organized together.
Object Creation Mode
The object Creation Mode delegates the creation of an object to another object. You can dynamically decide the instances of specific classes based on the context, you can also hide the details of how these instances are created and organized together.
All creation modes have two eternal themes: first, they encapsulate the information of specific classes used by the system; second, they hide how instances of these classes are created and organized. The outside world only knows the common interfaces of these objects, but does not know the specific implementation details. As a result, the creation mode provides the maximum flexibility for software designers in terms of what to create, who to create, and when to create.
For python, suppose there is a class like this:
Class person:
Def _ init _ (self, name ):
Self. Name = Name
To create an instance of this class, you should execute the following statement:
P = person ("Gary ")
However, if the work completed during object creation is complex, it takes a long time Code You cannot simply write all of them into the _ init _ method, because it violates two basic principles of Object-oriented Thinking: encapsulation and delegation ). If you insist on doing the same, the result will only make your code into a hard coding with fixed behavior, and the entire software structure is very likely to become very bad, because another module may be dependent on the instance you created, this increases the coupling between modules.
Encapsulate the creation process of a python object into a class to complete it separately, so that your Program It becomes more flexible and universal. Practice has proved that using the following six creation modes can better improve the object creation process:
Simple factory Mode
A dedicated class is defined to create instances of other classes. The created instance usually has a common parent class.
Factory method mode
The object is created by a standard method defined in the parent class, rather than its constructor. The specific subclass determines the object to be created.
Abstract Factory Mode
Provides a common interface to create multiple associated objects.
Singleton Mode
Ensure that the system generates only one instance of this type, and provide standard methods for accessing the instance to the outside world.
Builder Mode
The creation of complex objects is different from their specific representation (Representation), so that objects with different representations can be obtained as needed.
Prototype Mode
Using a class that can replicate itself makes it easier to dynamically create objects.
II. Introduction of Models
The simple factory mode is also called the static factory method mode, which belongs to the Creation Mode of the class. This mode, based on the information given by the outside world, is made by the "Factory" object "to produce an instance of some possible" product "class, all classes that the factory object can process generally inherit from the same parent class and provide the same interface to the outside world, except that the specific implementation will be different.
Suppose we want to develop a plotting program to draw simple ry, this software should be able to process the following ry objects:
Circle)
Rectangle)
Diamond)
In addition to their unique attributes and methods, almost all geometric figures can abstract two common methods: Drawing and erase, therefore, you can define a common interface shape for them. Although the Python language itself does not support interfaces, in order to better clarify the idea of the design pattern, we sometimes borrow the concept of interfaces in UML. In this way, the relationship between classes is shown in 1:
Figure 1
The shape interface defines the public methods that must be implemented for all geometric figures: Draw () and erase (). The Python code for implementing this interface is as follows. There is no interface concept in Python, therefore, you can use classes to replace them.
Code List 1: shape. py
Class shape:
# Drawing Images
Def draw (Self ):
Pass
# Erased graphics
Def erase (Self ):
Pass
The circle class is a specific form of shape. It implements all the methods defined by the shape interface. In addition, it adds an attribute _ radius to indicate the radius of the circle. The following code implements the circle class:
Code List 2: circle. py
Class circle (SHAPE ):
Def _ init _ (self, radius = 0 ):
Self. _ radius = radius
# Draw a circle
Def draw (Self ):
Print "draw circle"
# Erase a circle
Def erase (Self ):
Print "erase circle"
# Radius value method
Def getradius (Self ):
Return self. _ radius
# Radius Assignment Method
Def setradius (self, radius ):
Self. _ radius = radius
The rectangle class is also a specific form of shape. It implements all the methods defined by the shape interface and adds the _ width and _ HEIGHT attributes, the width and height of the rectangle. The following code 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
# Drawing a rectangle
Def draw (Self ):
Print "Draw rectangle"
# Erased rectangle
Def erase (Self ):
Print "erase rectangle"
# Value Method of width
Def getwidth (Self ):
Return self. _ width
# Width Assignment Method
Def setwidth (self, width ):
Self. _ width = width
# Height Value Method
Def getheight (Self ):
Return self. _ height
# Height Assignment Method
Def setheight (self, height ):
Self. _ Height = height
Similarly, the diamond class is also a specific form of shape. It implements all the methods defined in the shape interface and adds the _ width and _ HEIGHT attributes, represents the width and height of the diamond. The following code implements the diamond class:
Code list 4: Diamond. py
Class diamond (SHAPE ):
Def _ init _ (self, width = 0, Height = 0 ):
Self. _ width = width
Self. _ Height = height
# Drawing Diamond
Def draw (Self ):
Print "Draw diamond"
# Erase Diamond
Def erase (Self ):
Print "erase diamond"
# Value Method of width
Def getwidth (Self ):
Return self. _ width
# Width Assignment Method
Def setwidth (self, width ):
Self. _ width = width
# Height Value Method
Def getheight (Self ):
Return self. _ height
# Height Assignment Method
Def setheight (self, height ):
Self. _ Height = height
After all the geometric graphics classes are defined, the following is to provide a "Factory" class shapefactory to create specific instances of various geometric shapes. The role of the shapefactory class is to create different geometric objects, such as circles, rectangles, and diamond, according to external requirements ), in this way, the entire software architecture will be shown in 2.
Figure 2
The shapefactory class is used to create instances of various geometric shapes. The implementation 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
Only one method Factory () is defined in the shapefactory class. by calling this method, the outside world creates the required geometric object. However, if the requested class is not supported by the system, none is returned. After the factory class is introduced, if other modules want to generate instances of the geometric graphics class, they only need to call the factory () method of the shapefactory class:
FAC = shapefactory ()
Shape = FAC. Factory ("diamond ")
If shape! = None:
Shape. Draw ()
The Implementation Details of the class are successfully hidden from the outside. This is the basic strategy adopted by the simple factory model.
Iii. General Structure
The simple factory mode is a class creation mode. It is suitable for instantiating a large number of classes with common interfaces. It can be postponed until running to dynamically decide which class of instance to create.
This article from: China it live broadcasting room (http://www.itzbs.com)
Gof23Types of design patterns5Type:SingletonSingle-piece mode,Abstract FactoryAbstract Factory mode,BuilderGenerator mode,Factory methodFactory method mode,PrototypeOriginal mode. The following describes the design modes.
Design Mode |
GofDescription |
My understanding |
SingletonSingle-piece Mode |
Ensure that a class has only one instance and provides a global access point for the instance |
Control the number of object objects |
Abstract FactoryAbstract Factory Model |
provides an interface for creating a series of " related or interdependent objects " , no need to specify their specific classes |
Solve the Problem of object changes in a series |
BuilderGenerator Mode |
separates the construction of a complex object from its representation, so that different representations can be created during the same construction process |
You must create complex objects in the project. The so-called " complex objects " , indicates that this object also contains other sub-objects |
Factory methodFactory method mode |
Defines an interface for creating objects, so that the subclass decides to instantiate the class.FactorymethodDelay the instantiation of a class to the subclass |
The solution is to create an object. due to changes in requirements, this object is often subject to drastic changes, but the interfaces of this object are relatively stable. That is to say, branches often change, but branches and trunk interfaces are relatively stable. |
PrototypeOriginal Mode |
Use the prototype instance to specify the object type, and then copy the prototype to create a new object. |
The creation of some complex objects; due to changes in requirements, these objects often face drastic changes, but they have stable and consistent interfaces. |
In the course of learning, I think it is functionalAbstract FactoryMode andBuilderMode is easy to confuse,Factory methodMode andPrototypeThe mode is not easy to distinguish.SingletonThe mode is not too difficult. The following describes the first four modes.
I,Abstract FactoryMode andBuilderMode:
Abstract FactoryIs to deal with the problem of creating a series of objects, as in the previous sectionArticleFor example, to create a car object,Abstract FactoryThe Mode focuses more on the creation of a series of objects, or each part of the automobile type, such:Wheel,Engine,BodyAnd so on. In other words, the focus is on this series of objects.
BuilderIt is used to create a complex object, or to create sub-objects in the complex object. In the example of a car, I thinkAbstract FactoryMode,BuilderThe model focuses on the automobile type (the "complex object" mentioned above) and its parts (Wheel,Engine,BodyAnd so on.BuilderThe mode requires that the integration of various child types in this complex type (automobile) is relatively stable. The example shows that for an automobile, No matter what accessories are used for assembly, the assembly of each accessory is the same, there are relatively stable interfaces. What brand do you use for this car?WheelWhat brandEngineChanges may occur frequently.
II,Factory methodMode andPrototypeMode:
At first, I thought the two modes were the same in terms of functionality (personal opinion). They both encapsulated the creation of objects,PrototypeMode is usedPrototype cloneTo create an object, you should also pay attention to the differences between the shallow copy and the deep copy. After consulting with colleagues, I understood it. The two models are different in application scenarios.
Factory methodMode is to re-create an object
PrototypeThe mode is to clone existing objects. When two or more objects are the same, you can use a created object to clone other objects.