Python design mode: Creation Mode: Singleton mode and factory mode family, python Design Mode

Source: Internet
Author: User

Python design mode: Creation Mode: Singleton mode and factory mode family, python Design Mode
I. Singleton mode (Singleton)

The Singleton mode ensures that only one object instance exists at any time. In many cases, there is only one object in the system. All information is obtained from this object, such as the configuration object of the system or the thread pool. In these scenarios, the singleton mode is ideal.

To sum up, no matter how many times an object is initialized, the actually working object is generated only once and is generated for the first time.

There are many ways to implement the singleton mode using Python. First, let's look at the first method.

 

#! /Usr/bin/python3 #-*-coding: UTF-8-*-class singleton (object): "" Single Column mode "class _ A (object ): "The class that actually works is hidden from the outside. "Def _ init _ (self): pass def display (self):" returns the ID of the current instance, is the globally unique "return id (self) # class variable, used to store the _ A instance _ instance = None def _ init _ (self ): "first checks whether the _ A instance has been saved in the class variable. if not, creates one and returns" if singleton. _ instance is None: singleton. _ instance = singleton. _ A () def _ getattr _ (self, attr): return getattr (self. _ instance, attr) if _ name _ = "_ main _": # create two instances s1 = singleton () s2 = singleton () print (id (s1), s1.display () print (id (s2), s2.display ())
View Code

#! /Usr/bin/python3 #-*-coding: UTF-8-*-class singleton (object): "" Single Column mode "class _ A (object ): "The class that actually works is hidden from the outside. "Def _ init _ (self): pass def display (self):" returns the ID of the current instance, is the globally unique "return id (self) # class variable, used to store the _ A instance _ instance = None def _ init _ (self ): "first checks whether the _ A instance has been saved in the class variable. if not, creates one and returns" if singleton. _ instance is None: singleton. _ instance = singleton. _ A () def _ getattr _ (self, attr): return getattr (self. _ instance, attr) if _ name _ = "_ main _": # create two instances s1 = singleton () s2 = singleton () print (id (s1), s1.display () print (id (s2), s2.display ())

Output:
1917919737784 19179197378961917919738008 1917919737896
View Code

In the preceding single-column mode, the Singleton. _ instance class variable is used to store the created instance, and the instance is created only once. Since Python is a dynamic language, you can change the class definition at runtime. In the above Code, when Singleton is initialized for the first time, the instance of class _ A is generated for the first time and stored in Singleton. _ instance. _ instance obtains the instances that actually work, so that the singleton mode is realized.

From the output, we can see that although two instances are created (with different instance IDS), the IDS obtained when accessing their attributes are consistent. Although the above Code implements the singleton mode, this method is not flexible enough in real project development, because the classes that actually work must be built into the singleton class. We know that the modifier in Python is very useful. Can we make a singleton class into a decorator? The answer is yes. The following code is used.

#! /Usr/bin/python3 #-*-coding: UTF-8-*-import sqlite3from flask import current_appfrom flask import _ app_ctx_stack as stackclass SQLite3 (object ): def _ init _ (self, app = None): self. app = app if app is not None: self. init_app (app) def init_app (self, app): "" typical Flask extension Initialization Method "" app. config. setdefault ('sqlite3 _ database', ': memory:') app. teardown_appcontext (self. teardown) def connect (self): "connect to sqlite DATABASE" "return sqlite3.connect (current_app.config ['sqlite3 _ database']) def teardown (self, exception ): "Close sqlite link" ctx = stack. top if hasattr (ctx, 'sqlite3 _ db'): ctx. sqlite3_db.close () @ propertydef connection (self): "" Singleton mode here: Use flask. _ app_ctx_stack stores the sqlite link. Each time you obtain a database link, you can use connection to obtain "" ctx = stack. top if ctx is not None: if not hasattr (ctx, 'sqlite3 _ db'): ctx. sqlite3_db = self. connect () return ctx. sqlite3_db
View Code

 

In the above code, you can obtain the database connection through SQLite3.connection every time you use the database. SQLite3.connection ensures that the database connection only occurs once. Its principle is the same as that of the previous Singleton mode, except that the storage Instance becomes flask. _ app_ctx_stack.

With the above code, we can see that the singleton mode only needs to find a variable to store the created instance. Each time you obtain the instance, check whether the instance has been saved in the variable, if not, create an instance and save it to the variable. You can get the instance from the variable later. In Singleton mode, an instance is created only once.

Related Article

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.