A singleton pattern of design patterns

Source: Internet
Author: User

Usage scenarios:

In software development, software developers want some service classes and only one instance for other programs to use. Such as: the printer service program or some control of the system environment, in order to avoid inconsistencies caused by temples access, want to provide only one instance for other programs, as well as the environment to generate a unique sequence number or create an object need to consume too much resources (to access resources such as IO and database).

A global variable can be used for an object that is used by the entire system, and a unique instance can be guaranteed if the program is written correctly, but there is no guarantee that there is only one instance of the system if the system expands with it.

A class diagram of a singleton pattern:

Singleton mode is a relatively simple design pattern, which essentially instantiates itself and always provides a unique instance of a class to the system.

A singleton pattern implementation code:

Lazy mode:

 public  class   singleton{ static  Singleton singleton= private   Singleton () {}  public  static   Singleton Getsingleton () { if  (Singleton =null  ) {Singleton  = new   Singleton ();}  return   Singleton;}}  

This mode is thread insecure in multi-threaded concurrency mode, all in case of high concurrency problems, you can add the Synchronized keyword before the Getsingleton method, of course, you can also add synchronized keyword within the Getsingleton method, This is for Java, and if you use. NET, lock locks are used to achieve thread safety.

A Hungry man mode:

 Public class singleton{privatestaticfinal Singleton singleton=new  Singleton () ; Private Singleton () {}  Public Static Singleton Getsingleton () {return  Singleton;}}

A singleton pattern of design patterns

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.