A single-instance pattern of Python design Patterns (ii)

Source: Internet
Author: User

The last time we had a brief look at what a singleton pattern is, we continue to explore today.
Last content point this Python design pattern singleton mode (i)

Last time we were talking about the GOF design pattern, which means that a class has only one object. What we usually need is to have the instance share an identical configuration, such as a database connection. Alex Martelli's advice is that developers should focus on state and behavior rather than identity, so it's also known as Monostate (Single-state) mode.

Monostate The concept of a singleton pattern

First of all, the meaning of the word monostate, the design pattern of the name are very interesting, because in order to facilitate communication, memory, so the design pattern of the name of the pattern of the intention of the expression. Mono is a root, and Mono,mon in English means 1 meaning "state". Monostate means "single State", Monostate does not limit the number of objects created, but it has only one state

Monostate The use of single-case mode

We know that in Python, __dict__ is a dictionary used to store object properties whose key is the property name and the value of the property. So below we can use dict to store the state of all objects in a class. Consider the following example:

 class usedict:
__state={"Name":"Cxa"}
def __init__(self):
Self.age= -
Self.__dict__=self.__state
M=usedict ()
M1=usedict ()
M.age= at
Print (m)
Print (M1)
Print (m.__dict__)
Print (m1.__dict__)

Output results after running.

<__builtin__.usedict instance at0x7f78ceacc098>
<__builtin__.usedict instance at0x7f78ceacc128>
{' age ': at,' name ':' Cxa '}
{' age ': at,' name ':' Cxa '}

First we look at the results and we find that each time a new object is created for the Usedict instantiation, and then we modify the value of the Age property by M, the value of the age property of the M1 changes.
In addition, we can use the __new__ method itself to achieve.

 class usenew(object):
_state={}
def __new__(Cls,*args,**kwargs):
Obj=super (USENEW,CLS). __new__ (Cls,*args,**kwargs)
Obj.__dict__=cls._state
returnObj
A=usenew ()
A1=usenew ()
a.x=3
Print (a)
Print (A1)
Print (a.__dict__)
Print (a1.__dict__)

Here are the output results

<usenewObjectAt0x7f78ceb873d0>
<usenewObjectAt0x7f78ceb87b50>
{' x ':3}
{' x ':3}

The effect of the two formulations is the same.

How to implement a meta-class

A meta-class is a class of classes, which means that the class is an instance of its meta class. For a class that already exists, when the object needs to be created, the special method of Python is called __call__, and we can control the instantiation of an object by using the __call__ method of the Meta class, as shown in the following example
Example of a database connection

ImportPymysql
class Metasingleton(type):
_inst={}
def __call__(Cls,*args,**kwargs):
ifCls not inchCls._inst:
Cls._inst[cls]=super (METASINGLETON,CLS). __call__ (*args,**kwargs)
returnCLS._INST[CLS]

class mysqldb(Metaclass=metasingleton):
connection=None
def Conn(self):
ifSelf.connection is None:
self.connection= Pymysql.connect (host=' 127.0.0.1 ', port=3306, user=' Root ',
Passwd=' Aa1234 ', db=' user ', charset=' UTF8MB4 ')
Self.cursor=self.connection.cursor ()
returnSelf.cursor
D1=mysqldb (). Conn ()
D2=mysqldb (). Conn ()
Disadvantages of a singleton pattern

Introduction of such a long time of the singleton mode, perhaps you will have doubts, what is the disadvantage of the singleton mode?
While the singleton mode works fine but there are still some problems because the singleton has global access, the following issues may occur:

    • Multiple references to the same object may be created 。 Because a singleton creates only one object, a reference is created on an object in this case.

So far, we have introduced the singleton model of the relevant content, follow-up may write about other design patterns related articles, if you like, forward to the Friends circle and share it with the boys.

A single-instance pattern of Python design Patterns (ii)

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.