Design Mode-Singleton, design mode-

Source: Internet
Author: User

Design Mode-Singleton, design mode-

The Singleton mode is a common design mode.

The Singleton mode has the following features:

 1. A singleton class can only have one instance.
2. The Singleton class must create its own unique instance.
3. The Singleton class must provide this instance to all other objects.

 

Hungry Chinese Singleton

public class Singleton {    private static Singleton instance = new Singleton();    public static Singleton getInstance() {        return instance;    }}

When a class is created, a static object has been created for the system and will not be changed in the future.

 

Lazy Singleton

Public class Singleton {private static Singleton instance = null;/*** lazy Mode 1 * Synchronization Method */public static synchronized Singleton getInstance () {if (instance = null) {instance = new Singleton ();} return instance;}/*** lazy Mode 2 * synchronization code block */public static Singleton getInstance () {synchronized (Singleton. class) {if (instance = null) {instance = new Singleton () ;}} return instance ;}}

Low efficiency when synchronizing code or code blocks

 

Double lock check

public class Singleton {    private static volatile Singleton instance = null;    public static Singleton getInstance() {        if (instance == null) {            synchronized (Singleton.class) {                if (instance == null) {                    instance = new Singleton();                }            }        }        return instance;    }}

Thread security to improve efficiency

 

Internal static class

public class Singleton {    private static class SingletonHandler {        private static Singleton instance = new Singleton();    }    public static Singleton getInstance() {        return SingletonHandler.instance;    }}

 

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.