Android design mode (1) ---- Singleton Mode

Source: Internet
Author: User

Android design mode (1) ---- Singleton Mode

Among many design patterns, I believe that the design patterns most programmers first came into contact with are the singleton model. Of course, I am no exception. The Singleton mode should be the simplest of all design patterns. The Singleton mode is simple, but if you go deep into the singleton mode, it will involve a lot of knowledge. I will continue to update this article. The Singleton mode provides an object throughout the system, and then the entire system uses this object. This is the purpose of the singleton mode.

I. Full Chinese Style singleton:

Public class Singleton {/*** Singleton object instance */private static Singleton instance = null; public static Singleton getInstance () {if (instance = null) {instance = new Singleton ();} return instance ;}}

Ii. Hunger type singleton:

Public class Singleton {/*** Singleton object instance */private static Singleton instance = new Singleton (); public static Singleton getInstance () {return instance ;}}

These two Singleton models often fail to meet the requirements in actual code. Therefore, we need to rewrite these Singleton models according to our own needs,

For example, if other parameters are required for the created singleton object, we need to rewrite it as follows:

Public class Singleton {/*** Singleton object instance */private static Singleton instance = null; public static Singleton getInstance (Context context) {if (instance = null) {instance = new Singleton (context);} return instance ;}}

For example, in the case of resource sharing, multi-thread concurrent access is required. In this case, we should do this:

Public class Singleton {/*** Singleton object instance */private static Singleton instance = null; public synchronized static Singleton getInstance () {if (instance = null) {instance = new Singleton ();} return instance ;}}

In fact, no matter what conditions, no matter how you change it, it is a variant of the two Singleton modes !!!!


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.