Singleton Design Mode

Source: Internet
Author: User

Singleton design model:Ensure that a class has only one instance and provides a global access point to it.

 

Objective: Singleton is a creation-based design model that mainly solves the problem of object creation.

Ensure that the class has only one function, that is, creating its own instance. Because there is only one global change point, that is, creating an object.

The following are instances in a single thread:

Public class Singleton {<br/> Public static Singleton instance = NULL; <br/> private Singleton () {</P> <p >}< br/> Public static Singleton getinstance () {<br/> If (instance = NULL) {<br/> instance = new Singleton (); <br/>}< br/> return instance; <br/>}< br/>}

 

Public class singletona {<br/> private singletona () {</P> <p >}< br/> static class singletonholder {<br/> static singletona instance = new singletona (); <br/>}</P> <p> Public static singletona getinstance () {<br/> return singletonholder. instance; <br/>}< br/> Public static void main (string [] ARGs) {<br/> singletona singlea = singletona. getinstance (); <br/> singletona singleb = singletona. getinstance (); <br/> system. out. println (singlea. hascode (); <br/> system. out. println (stringb. hascode (); <br/>}< br/>}

Multithreading

Public class singletonb {<br/> Public static singletonb instance = NULL; <br/> Public synchronized static singletonb getinstance () {<br/> If (instance = NULL) {<br/> instance = new singletonb (); <br/>}< br/> return instance; <br/>}< br/> private singletonb () {</P> <p >}< br/>}

Main Purpose: database connection/user group type/

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.