Design Mode: Singleton mode and Design Mode

Source: Internet
Author: User

Design Mode: Singleton mode and Design Mode
Single Instance, as its name implies, is a single instance

 

1. Advantages of Singleton Mode
  • In Singleton mode, only one object is generated, which reduces system overhead. When an object requires a large amount of resources, such as reading the configuration file and generating other dependent objects, then, a singleton object can be directly generated when the application is started. And then permanently resident in the memory to solve the problem.
  • In Singleton mode, you can set global access points. Optimize access to shared resources. For example, you can design a singleton class to map all data tables.

 

2. Implementation of Singleton

Let's look at a common scenario:

This normal method will consume memory in the case of a large amount of traffic!

When each request arrives, you need to create an instance in the memory and then execute the specified method through the instance.

The problem arises... if the concurrency is large, there will be a lot of memoryObjects with identical functions.

#! /Usr/bin/env python # coding: utf-8from wsgiref. simple_server import make_serverclass DbHelper (object): def _ init _ (self): self. hostname = '1. 1.1.1 'self. port = 3306 self. password = 'pwd' self. username = 'root' def fetch (self): # connect to the database # concatenate an SQL statement # operate return 'fetch' def create (self ): # connecting to the database # splicing SQL statements # operating 'create' def remove (self): # connecting to the database # splicing SQL statements # operating 'delete' def modify (self ): # connecting to the database # splicing SQL statements # operating return 'modify' class Handler (object): def index (self): # creating an object db = DbHelper () print id (db) db. fetch () return 'index' def news (self): return 'News' def RunServer (environ, start_response): start_response ('200 OK ', [('content-type ', 'text/html')]) url = environ ['path _ info'] temp = url. split ('/') [1] obj = Handler () is_exist = hasattr (obj, temp) if is_exist: func = getattr (obj, temp) ret = func () return ret else: return '404 not found 'if _ name _ =' _ main _ ': httpd = make_server ('', 8001, RunServer) print "Serving HTTP on port 8001... "httpd. serve_forever ()

 

 

The above example is about database operations. When the operation volume is very large, it will produce a large amount of memory consumption, because each request creates an instance

For objects with the same functions, you can create only one in the memory and call them when necessary. This is also an excellent solution !!!

The Singleton mode is used to ensure memory usage.Only one instance exists!!! @ Classmethod or static method@ StaticmethodAll can be implemented 

Principle: constructs a singleton mode based on object-oriented features:

  • Class Method @ classmethod (cls = current class) the trigger is a class that is called directly using a class. There can only be one parameter cls in the brackets.Only one parameter is required for static methods. The current class is automatically passed in when the parameter is passed in. Used in singleton mode.
  • The static method belongs to the @ staticmethod trigger class. There can be multiple parameters without parameters () in brackets.Class plus static method = a function. You can access the method by creating an object, just like creating a function. Static methods are useful only when all programs require object-oriented functions instead of functions.

 

Why are there class and static methods?

If the two methods are not available, an object will be created before calling the method. Both methods can be called directly through classes to save memory. 
#! /Usr/bin/env python # coding: utf-8from wsgiref. simple_server import make_server ############ Singleton class definition ########### class DbHelper (object ):_ Instance = None# Create a private static field to save the instance field def _ init _ (self): self. hostname = '1. 1.1.1 'self. port = 3306 self. password = 'pwd' self. username = 'root' @ staticmethod def singleton (): if DbHelper. _ instance: return DbHelper. _ instance else: DbHelper. _ instance = DbHelper () return DbHelper. _ instance def fetch (self): # connecting to the database # splicing SQL statements # operation pass def create (self): # connecting to the database # splicing SQL statements # operation pass def remove (self): # connecting to the database # splicing SQL statements # operation pass def modify (self): # connecting to the database # splicing SQL statements # operating passclass Handler (object): def index (self ): obj = DbHelper. singleton () # directly call the static method print id (obj) obj through the class. create () return 'index' def news (self): return 'News' def RunServer (environ, start_response): start_response ('2014, 200 OK ', [('content-type ', 'text/html')]) url = environ ['path _ info'] temp = url. split ('/') [1] obj = Handler () is_exist = hasattr (obj, temp) if is_exist: func = getattr (obj, temp) ret = func () return ret else: return '404 not found 'if _ name _ =' _ main _ ': httpd = make_server ('', 8001, RunServer) print "Serving HTTP on port 8001... "httpd. serve_forever ()

 

  

 

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.