A single-instance pattern of Python design patterns

Source: Internet
Author: User

1. due to the different characteristics of the language, the design mode and implementation of the difficulty will be different

2. Some patterns have been built into the language, such as the iterator pattern.

3. The singleton mode can be directly implemented with module-level variables .

4. Normal Factory mode can be implemented directly by passing in "class name" as parameter

Singleton Mode Example:

12_eg.py

Class Singleclass:

def __init__ (self,x=0):

self.x = 0

sc = Singleclass ()

Def TSC ():

Print (sc.x)

sc.x = 10

Print (sc.x)

Def TSC2 ():

Print (sc.x)

sc.x = 9

Print (sc.x)

if __name__ = = ' __main__ ':

TSC ()

TSC2 ()

The running result of the program is:

12_egs.py

Class Singleton:

def __new__ (Cls,*args,**kwargs):

If not hasattr (CLS, ' _SGL '):

CLS._SGL = Super (). __new__ (Cls,*args,**kwargs)

Return CLS._SGL

if __name__ = = ' __main__ ':

SA = Singleton ()

SB = Singleton ()

Print (ID (SA))

Print (ID (SB))

The running result of the program is:

Implemented by passing in the "class name" as a parameter:

12_eg2.py

Class Ab:

A = 3

Class Ac:

A = 0

Class MyFactory:

def get_instance (self,ins):

return ins ()

if __name__ = = ' __main__ ':

MF = myfactory ()

Print (Type (mf.get_instance (Ab)))

Print (Type (mf.get_instance (Ac)))

The running result of the program is:

original link:http://www.maiziedu.com/wiki/python/designpattern/

A single-instance pattern of Python design patterns

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.