This is the 12th day of my participation in the August More Text Challenge. For details, see:August is more challenging
📖 preface
Do what I can, do what I can, do what I can.
The more transparent something is, the more mysterious it is. The universe itself is transparent. You can see as far as you want as you can see, but the more you look, the more mysterious it becomes. – liu
When I first learn the design pattern, I will be confused about the practical application of the three factory modes. In fact, the three modes have their own advantages and disadvantages and the application scenarios are not the same:
- Simple factory pattern: This is useful when the number of objects to be created is small, the business logic in the factory method is not too complex, and the user only cares about what type of instance is being created, not the initialization process, such as multiple database (MySQL/MongoDB) instances, multiple file format parser (XML/JSON), etc.
- Factory method pattern: Inherits the advantages of the simple factory pattern and improves it. Instead of a factory class being responsible for all product creation, the factory method pattern allows the system to be extended more efficiently. The actual application can be used to realize the system of the log system, such as specific program run log, network log, database log can be used to create specific factory class.
- The abstract factory pattern: on the basis of the factory method extends the factory’s support for multiple products to create, more suitable for some large systems, such as system, which has more than one product family, and species of these products need to implement the same interface, like many software system interface under different themes in different button, text box, type and so on. (More on this in the next post)
💕 Simple factory
First, let’s look at a simple example:
#coding=utf-8
class Mercedes(object):
"""奥迪
"""
def __repr__(self):
return "AUDI"
class BMW(object):
"""宝马
"""
def __repr__(self):
return "BMW"
Copy the code
Suppose we have two “products”, AUDI and BMW cars. If there is no “factory” to produce them, we will instantiate them ourselves in the code, such as:
audi = AUDI()
bmw = BMW()
Copy the code
But in reality, you might have a lot of automotive products, and each product has different construction parameters, so you might have trouble creating instances. You can then construct a “simple factory” that encapsulates all the car instantiation processes.
Class staticEcarFactory (object): """ "@staticMethod def product_car(name): if name == 'AD ': return AUDI() elif name == 'bmw': return BMW()Copy the code
With the SimpleCarFactory class in place, you can get the desired object instance by passing parameters to a fixed interface, as follows:
c1 = SimpleCarFactory.product_car('ad')
c2 = SimpleCarFactory.product_car('bmw')
Copy the code
🎎 Factory mode:
Factories produce different products based on the different materials they provide. Then in the programming design pattern, according to provide different user input, call the same interface, get different results.
Example 1:
When writing a Web framework, we need to consider that users may connect to a variety of databases, but we can’t predict which database they will use. So we provide a general method, it contains various database connection scheme, users in the use process, you just need to pass into the database name and connection information, you need to get a fixed | | for the selected user database connection string.
Code:
def connect(db, *arg, **kwargs):
db = db.lower()
dbname = kwargs['db']
if db == 'mysql':
result = "mysql+pymysql://{username}:{password}@{server}/{dbname}".format(username = kwargs['username'], password = kwargs['password'], server = kwargs['server'], dbname=dbname)
elif db == 'postgresql:
result = 'postgresql://{username}:{passwrod}@{server}/{dbname}'.format(susername = kwargs['username'], password = kwargs['password'], server = kwargs['server'], dbname=dbname)
return result
Copy the code
You can see:
If the user input is ‘MySQL’, then the factory method returns a connection string for the user to connect to the MySQL database. (Connect using Pymysql)
If the user enters’ postgresQL ‘, the user will get a connection string to connect to the PostgresQL database. It’s more of the same principle. Install Psycopg2 for connection.
If you don’t understand the above example, move on to the following example:
In the actual development process, it is divided into production mode and development mode, so I can also use the factory mode to output different commands in different modes and call the same interface to complete the configuration implementation in different environments.
Example 2:
Pass class DevelopConfig(config): DEBUG = True LOG_LEVEL = logging.DEBUG class ProductConfig(Config): LOG_LEVEL = logging.ERROR config = { "development": DevelopConfig, "production": ProductConfig} def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name])Copy the code
That is: when you enter “development”, the configuration file for the development environment is loaded, and “production”, the configuration file for the production environment is loaded.
🎉 summary
-
It’s very elementary and very violent. It’s just an infinite list of things to consider and what to do about them.
-
For more references, see here:Chen Yongjia’s Blog
-
Like the little friend of the blogger can add a concern, point a like oh, continue to update hey hey!