Design Patterns in Android development-a detailed explanation of the singleton pattern

Source: Internet
Author: User

Design Patterns in Android development-a detailed explanation of the singleton pattern:
1. Characteristics of the singleton mode:
(1). Ensure that there is only one instance of a class
(2). Provides a global access point that can be accessed to him.
(3). The constructor is declared private, thereby preventing the creation of objects outside the class
2. Type:
(1). A hungry man single-case mode
(2). Lazy single-case mode
3. Code Analysis:
(1). A hungry man single-case mode:

  //类加载的时候对象就实例化了。  privatestaticnew Single();    publicstaticgetInstance() {        return mSingle;    //缺点:不能保证有其他的方式导致类加载,这时候对象实例化没有达到延迟加载的效果      

(2). Lazy Singleton mode: (thread-safe), (second use this way)

publicstaticgetInstance2() {        synchronized (Single.class) {            ifnull) {                new Single();            }        }        return mSingle2;    }  //这个类只有一个实例,在多线程的时候也是创建一个实例。同一时间内只有一个线程调用这个方法,若有多个线程同时访问这个方法的话,其它的线程必须等待。//如果没有这个关键字,在多线程的时候就会创建两个或者多个实例.这种方式效率比较低。

(3). Internal class Mode: (Recommended Use this way)

privatestaticclass SingleHolder {       privatestaticnew Single();    }publicstaticgetInstance03() {     return//保证了对象初始化的时候只有一个线程。类加载的时候也没有主动初始化对象。只是在调用getInstance03()方法的时候加载了SingleHolder。达到了延迟加载的效果。

Design Patterns in Android development-a detailed explanation of the singleton pattern

Related Article

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.