zbb20180930 design mode-Singleton mode

Source: Internet
Author: User

Singleton mode What is a singleton mode?

A singleton guarantees that only one instance of an object JVM can be used , and a common singleton lazy-a hungry man-

What is lazy , is needed to instantiate , thread is unsafe.

What is a hungry man is that when the class file is loaded, it is initialized and inherently thread-safe.

One-Example Lazy code

class singletontest {

public static void main (string[] args ) {

Singleton SL1 = Singleton. Getsingleton ();

Singleton SL2 = Singleton. Getsingleton ();

System. out . println (sl1 = = sl2);

}

}

Public class Singleton {

// when needed, will be instantiated

private static Singleton Singleton;

Private Singleton () {

}

synchronized public static Singleton Getsingleton () {

if (singleton = = null) {

singleton = new Singleton ();

}

return Singleton;

}

}

Double Test lock

// Lazy Type Second writing efficiency high double test lock

static public Singleton GetSingleton2 () {

if (singleton = = null) { // First Step inspection lock

synchronized (Singleton. class ) { // Second Step inspection lock

if (singleton = = null) {

singleton = new Singleton ();

}

}

}

return Singleton;

}

A Hungry Man type code

class SingletonTest1 {

public static void Main (string[] args >) {

Singleton1 SL1 = Singleton1. Getsingleton ();

Singleton1 SL2 = Singleton1. Getsingleton ();

System. out . println ((sl1 = = sl2) +"-");

}

}

Public class Singleton1 {

// when class file is loaded and initialized

private static Singleton1 singleton = new Singleton1 ();

Private Singleton1 () {

}

public static Singleton1 Getsingleton () {

return Singleton;

}

}

zbb20180930 design mode-Singleton mode

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.