Android Single-instance mode

Source: Internet
Author: User

Characteristics of the single-case mode:

1. Only one instance of a class

2. Create this instance yourself

3, the entire system to use this example

The form of a singleton pattern:

1, a Hungry man type single case

publicclassSingleton {

privateSingleton(){}

//在自己内部定义自己一个实例,是不是很奇怪?

//注意这是private 只供内部调用

privatestatic Singleton instance = newSingleton();

//这里提供了一个供外部访问本class的静态方法,可以直接访问

publicstaticSingleton getInstance() {

returninstance;

}

}

2、懒汉式单例类

privatestaticSingleton instance = null;

publicstaticsynchronized Singleton getInstance() {

//这个方法比上面有所改进,不用每次都进行生成对象,只是第一次

//使用时生成实例,提高了效率!

if(instance==null)

instance=newSingleton();

returninstance; }

}

The second form is the lazy initialization, that is, the first call when the initial singleton, and then no longer generated.

Note that synchronized in the form of lazy initialization, this synchronized is important, if there is no synchronized, then using getinstance () is possible to get multiple singleton instances.
Generally the first is more secure

3, the more commonly used are:

publicclassSingleton {

privatevolatile staticSingleton singleton;

privateSingleton(){}

publicstaticSingleton getInstance(){

if(singleton==null){

synchronized(Singleton.class){

if(singleton==null){

singleton=newSingleton();

}

}

还可以参考一下android的Activity加载模式:

1、singleTop

2、singleTask

3、singleInstance

Android Single-instance 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.