Singleton mode of Android design mode series

Singleton mode is the simplest of the 23 design modes of GOF.

Compared with other modes, this mode is relatively independent. It is only responsible for controlling its single instantiation number (rather than considering what kind of instances to generate for users). It is very interesting. It feels very clean. I like this mode very much. The singleton pattern is used in many places in Android. This paper takes the input method manager inputmethodmanager as an example to analyze. Singleton pattern, with its unique advantages, can replace the global variables in the system and is widely used.

1. Intention

Ensure that a class has only one instance and provide a global access point to access it. Hot words: Singleton unique private structure

2. Structure

There are many system level global variables in Android, such as time, input method, account, status bar, etc. the singleton mode is used directly or indirectly in Android.

Taking the input method as an example, modify the above figure to the actual situation:

It's very simple, but we also see the synchronized keyword from the above. In a multi-threaded environment, the single instance mode will certainly do concurrency control in order to ensure the uniqueness of its own number of instances.

Such thread safe singletons, cross process singletons, parameterized singletons and so on are indeed beyond the scope of this article, and they all involve many things. They are a big topic and difficult to expand.

3. Code:

The client calls, such as the following calls in the getsystemservice () method in contextimpl:

A very simple, clean model.

4. Effect

(1). Create a pattern.

(2). Controlled access to unique instances.

(3). Avoid global variables contaminating namespaces.

(4). Allows refinement of operations and representations.

(5). More flexible than class operations.

The above is a single example of the Android design pattern series introduced by Xiaobian. I hope it will help you. If you have any questions, please leave me a message and Xiaobian will reply to you in time. Thank you very much for your support for the programming tips website!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>