The ubiquitous design pattern in Android Development--singleton mode

Source: Internet
Author: User
<span id="Label3"></p><p><p>For developers, design patterns are sometimes a hurdle, but design patterns are very useful, after this hurdle, it can let you level up a Grade. In the development of android, it is necessary to understand some design patterns. For students who want to learn the design pattern of the system, 2 books are recommended Here. One is head first series head Hirst Design Pattern, English Good can read english, can read a few times More. The other one is the big talk design Pattern.</p></p><p><p>This article introduces a pattern, the singleton pattern, because the individual feels that this pattern is easiest to understand and not too complex.</p></p><p><p>First understand what a singleton is, and what you can hear from the name is to maintain the unique object in Memory. There are several advantages to doing this:</p></p> <ul> <ul> <li>For those classes that consume more memory, only one instantiation can greatly improve performance, especially in mobile Development.</li> <li>There is always only one instance in memory when you keep the program running</li> </ul> </ul><p><p>In fact, there are many ways to achieve a single case, but individuals tend to have more than 1 of Them. You can see the singleton mode</p></p><p><p>The code is as follows</p></p> <pre name="code" class="prettyprint prettyprinted" data-original-code="public class Singleton { private static volatile Singleton instance = null; private Singleton(){ } public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; }}" data-snippet-id="ext.84f27e94254a1d6ff0d80c65c52282a6" data-snippet-saved="false" data-csrftoken="WuBuQk7n-nJajP96vxtRcZmmHZtxaHm7SP3o" data-codota-status="done"><code class="hljs cs has-numbering"><code class="hljs cs has-numbering"><span class="hljs-keyword">public <span class="hljs-keyword">class Singleton { <span class="hljs-keyword">private <span class="hljs-keyword">static <span class="hljs-keyword">volatile Singleton instance = <span class="hljs-keyword">null; <span class="hljs-keyword">private <span class="hljs-title">Singleton(){ } <span class="hljs-keyword">public <span class="hljs-keyword">static Singleton <span class="hljs-title">getInstance() { <span class="hljs-keyword">if (instance == <span class="hljs-keyword">null) { synchronized (Singleton.class) { <span class="hljs-keyword">if (instance == <span class="hljs-keyword">null) { instance = <span class="hljs-keyword">new Singleton(); } } } <span class="hljs-keyword">return instance; }}</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></code></code></pre><p><p></p></p><p><p></p></p><p><p>To ensure a single case, you need to do a few steps</p></p> <ul> <ul> <li>You must prevent external calls to the constructor to instantiate, so the constructor must be Privatized.</li> <li>You must define a static function to obtain the singleton</li> <li>Single case using volatile modifiers</li> <li>Using synchronized for synchronous processing, and double-judging Whether it is null, we see that synchronized (singleton.class) is also null-judged, because one thread enters the code, and if another thread waits , when the previous thread has created an instance, and the other thread gets the lock into the synchronization code, the instance already exists and there is no need to create it again, so the decision is null or NECESSARY.</li> </ul> </ul><p><p>For a singleton concurrency test, you can use Countdownlatch to wait for the lock to release using await (), and use Countdown () to release the lock to achieve the concurrency Effect. You can see the following code</p></p><pre name="code" class="prettyprint prettyprinted" data-original-code="public static void main(String[] args) { final CountDownLatch latch = new CountDownLatch(1); int threadCount = 1000; for (int i = 0; i < threadCount; i++) { new Thread() { @Override public void run() { try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Singleton.getInstance().hashCode()); } }.start(); } latch.countDown();}" data-snippet-id="ext.021fffc00f359fe7464e211fe805fac2" data-snippet-saved="false" data-csrftoken="DbRdXo7B-8ijRtHpchUid61UaHNK-hG-ljkA" data-codota-status="done"><code class="hljs cs has-numbering"><span class="hljs-keyword">Public<span class="hljs-keyword"><span class="hljs-keyword">static <span class="hljs-keyword">void <span class="hljs-title">main (String[] Args) { Final Countdownlatch latch = <span class="hljs-keyword">new countdownlatch (<span class="hljs-number">1); <span class="hljs-keyword">int threadcount = <span class="hljs-number">1000; <span class="hljs-keyword">for (<span class="hljs-keyword">int i = <span class="hljs-number">0; i < threadCount; i+ +) {<span class="hljs-keyword">new Thread () {@Override <span class="hljs-keyword">public <span class="hljs-keyword">void <span class="hljs-title">run () {<span class="hljs-keyword">try {latch.<span class="hljs-keyword">await (); } <span class="hljs-keyword">catch (interruptedexception e) {e.printstacktrace ();} System. <span class="hljs-keyword">out.println (singleton.getinstance (). hashcode ());} }.start (); } latch.countdown ();} </span> </span> </span> </span> </span> </span> </span> </span> </span> </span> </span> </span> </span> </span> </span></span></span></span></span></span></code></pre><p><p></p></p><p><p></p></p><p><p>Look at the print out of the hashcode will not appear different can, theoretically, all the Same.</p></p><p><p>In android, a single case is used in many Places.</p></p><p><p>such as the single case in Android-universal-image-loader</p></p> <pre name="code" class="prettyprint prettyprinted" data-original-code="private volatile static ImageLoader instance;/** Returns singleton class instance */public static ImageLoader getInstance() { if (instance == null) { synchronized (ImageLoader.class) { if (instance == null) { instance = new ImageLoader(); } } } return instance;}" data-snippet-id="ext.39491460780c9848f94a40614ef83f46" data-snippet-saved="false" data-csrftoken="qW1fnQ3c-_v8vf0QSmAPNxwvLuK0xaEHOU0w" data-codota-status="done"><code class="hljs java has-numbering"><code class="hljs java has-numbering"><span class="hljs-keyword">private <span class="hljs-keyword">volatile <span class="hljs-keyword">static ImageLoader instance;<span class="hljs-javadoc">/** Returns singleton class instance */<span class="hljs-keyword">public <span class="hljs-keyword">static ImageLoader <span class="hljs-title">getInstance() { <span class="hljs-keyword">if (instance == <span class="hljs-keyword">null) { <span class="hljs-keyword">synchronized (ImageLoader.class) { <span class="hljs-keyword">if (instance == <span class="hljs-keyword">null) { instance = <span class="hljs-keyword">new ImageLoader(); } } } <span class="hljs-keyword">return instance;}</span></span></span></span></span></span></span></span></span></span></span></span></span></span></code></code></pre><p><p></p></p><p><p></p></p><p><p>such as the single case in Eventbus</p></p> <pre name="code" class="prettyprint prettyprinted" data-original-code="private static volatile EventBus defaultInstance;public static EventBus getDefault() { if (defaultInstance == null) { synchronized (EventBus.class) { if (defaultInstance == null) { defaultInstance = new EventBus(); } } } return defaultInstance;}" data-snippet-id="ext.4db4a4fbb3d25dbb40cd43b89f9147bd" data-snippet-saved="false" data-csrftoken="7YT8UrzO-WqBo34NMORtlFFVIccmzw7A3DRY" data-codota-status="done"><code class="hljs java has-numbering"><code class="hljs java has-numbering"><span class="hljs-keyword">private <span class="hljs-keyword">static <span class="hljs-keyword">volatile EventBus defaultInstance;<span class="hljs-keyword">public <span class="hljs-keyword">static EventBus <span class="hljs-title">getDefault() { <span class="hljs-keyword">if (defaultInstance == <span class="hljs-keyword">null) { <span class="hljs-keyword">synchronized (EventBus.class) { <span class="hljs-keyword">if (defaultInstance == <span class="hljs-keyword">null) { defaultInstance = <span class="hljs-keyword">new EventBus(); } } } <span class="hljs-keyword">return defaultInstance;}</span></span></span></span></span></span></span></span></span></span></span></span></span></code></code></pre><p><p></p></p><p><p></p></p><p><p>The above single case is more orderly, of course, there are actually many of the singleton are changed a look, single nature or single Case.</p></p><p><p>such as the single case in Inputmethodmanager</p></p> <pre name="code" class="prettyprint prettyprinted" data-original-code="static InputMethodManager sInstance;public static InputMethodManager getInstance() { synchronized (InputMethodManager.class) { if (sInstance == null) { IBinder b = ServiceManager.getService(Context.INPUT_METHOD_SERVICE); IInputMethodManager service = IInputMethodManager.Stub.asInterface(b); sInstance = new InputMethodManager(service, Looper.getMainLooper()); } return sInstance; }}" data-snippet-id="ext.b345a8192f014a703944fbdece936e5f" data-snippet-saved="false" data-csrftoken="LDCCxtLR-d6TuIW_1l1cK8gvfqCYqHTlh4n4" data-codota-status="done"><code class="hljs java has-numbering"><code class="hljs java has-numbering"><span class="hljs-keyword">static InputMethodManager sInstance;<span class="hljs-keyword">public <span class="hljs-keyword">static InputMethodManager <span class="hljs-title">getInstance() { <span class="hljs-keyword">synchronized (InputMethodManager.class) { <span class="hljs-keyword">if (sInstance == <span class="hljs-keyword">null) { IBinder b = ServiceManager.getService(Context.INPUT_METHOD_SERVICE); IInputMethodManager service = IInputMethodManager.Stub.asInterface(b); sInstance = <span class="hljs-keyword">new InputMethodManager(service, Looper.getMainLooper()); } <span class="hljs-keyword">return sInstance; }}</span></span></span></span></span></span></span></span></span></code></code></pre><p><p></p></p><p><p></p></p><p><p>Accessibilitymanager in the single case, see the code so long, in fact, is to make some judgments, or a single case</p></p><pre name="code" class="prettyprint prettyprinted" data-original-code="private static AccessibilityManager sInstance;public static AccessibilityManager getInstance(Context context) { synchronized (sInstanceSync) { if (sInstance == null) { final int userId; if (Binder.getCallingUid() == Process.SYSTEM_UID || context.checkCallingOrSelfPermission( Manifest.permission.INTERACT_ACROSS_USERS) == PackageManager.PERMISSION_GRANTED || context.checkCallingOrSelfPermission( Manifest.permission.INTERACT_ACROSS_USERS_FULL) == PackageManager.PERMISSION_GRANTED) { userId = UserHandle.USER_CURRENT; } else { userId = UserHandle.myUserId(); } IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE); IAccessibilityManager service = IAccessibilityManager.Stub.asInterface(iBinder); sInstance = new AccessibilityManager(context, service, userId); } } return sInstance;}" data-snippet-id="ext.8d187adee04ae853f8a4f26f384b28af" data-snippet-saved="false" data-csrftoken="4dJfPXf9-Mf4z5Lr97xzT_4admgN2Qzxi-Z0" data-codota-status="done"><code class="hljs java has-numbering"><span class="hljs-keyword">Private<span class="hljs-keyword">Static Accessibilitymanager sinstance;<span class="hljs-keyword">Public<span class="hljs-keyword">Static Accessibilitymanager<span class="hljs-title">GetInstance (context Context) {<span class="hljs-keyword"><span class="hljs-keyword">synchronized (sinstancesync) {<span class="hljs-keyword">if (sInstance = = <span class=" Hljs-keyword ">null" {<span class="hljs-keyword">final <span class="hljs-keyword">int userId; <span class="hljs-keyword">if (binder.getcallinguid () = = Process.system_uid | | context.checkcallingorselfpermission (Manifest.permission.INTERACT_ACROSS_USERS) = = Packagemanager.permission_granted | | Context.checkcallingorselfpermission (Manifest.permission.INTERACT_ACROSS_USERS_FULL) = = Packagemanager.permission_granted) {userId = userhandle.user_current;} <span class="hljs-keyword">else {userId = Userhandle.myuserid ();} IBinder IBinder = Servicemanager.getservice (context.accessibility_service); Iaccessibilitymanager Service = IAccessibilityManager.Stub.asInterface (ibinder); Sinstance = <span class="hljs-keyword">new accessibilitymanager (context, service, userId);}} <span class="hljs-keyword">return sinstance;} </span> </span> </span> </span> </span> </span> </span> </span> </span></span></span></span></span></span></span></code></pre><p><p></p></p><p><p></p></p><p><p>Of course, There are many kinds of examples, such as the Bad Han style, interested in their own to understand it.</p></p><p><p>finally, we apply a singleton pattern. A typical application is to manage our activity, which can be used as a tool class, and the code is simple and does not explain anything.</p></p><pre name="code" class="prettyprint prettyprinted" data-original-code="public class ActivityManager { private static volatile ActivityManager instance; private Stack<Activity> mActivityStack = new Stack<Activity>(); private ActivityManager(){ } public static ActivityManager getInstance(){ if (instance == null) { synchronized (ActivityManager.class) { if (instance == null) { instance = new ActivityManager(); } } return instance; } public void addActicity(Activity act){ mActivityStack.push(act); } public void removeActivity(Activity act){ mActivityStack.remove(act); } public void killMyProcess(){ int nCount = mActivityStack.size(); for (int i = nCount - 1; i >= 0; i--) { Activity activity = mActivityStack.get(i); activity.finish(); } mActivityStack.clear(); android.os.Process.killProcess(android.os.Process.myPid()); }}" data-snippet-id="ext.608f66d10fdff6ed00efbc7f1da79657" data-snippet-saved="false" data-csrftoken="FYnEyihx-HThe5yDZmYHxN69KoghnvlRVy8E" data-codota-status="done"><code class="hljs cs has-numbering"><span class="hljs-keyword">Public<span class="hljs-keyword">Class Activitymanager {<span class="hljs-keyword">Private<span class="hljs-keyword">Static<span class="hljs-keyword">Volatile Activitymanager instance;<span class="hljs-keyword">Private stack<activity> Mactivitystack =<span class="hljs-keyword">New Stack<activity> ();<span class="hljs-keyword">Private<span class="hljs-title">Activitymanager () {}<span class="hljs-keyword">Public<span class="hljs-keyword">Static Activitymanager<span class="hljs-title">GetInstance () {<span class="hljs-keyword">if (instance = =<span class="hljs-keyword">Null) {synchronized (activitymanager.class) {<span class="hljs-keyword">if (instance = =<span class="hljs-keyword">Null) {instance =<span class="hljs-keyword">New Activitymanager (); } }<span class="hljs-keyword"><span class="hljs-keyword">return instance;} <span class="hljs-keyword">public <span class="hljs-keyword">void <span class="hljs-title">addacticity (Activity Act) {mactivitystack.push (act);} <span class="hljs-keyword">public <span class="hljs-keyword">void <span class="hljs-title">removeactivity (Activity Act) {mactivitystack.remove (act);} <span class="hljs-keyword">public <span class="hljs-keyword">void <span class="hljs-title">killmyprocess () { <span class="hljs-keyword">int ncount = Mactivitystack.size (); for <span class="hljs-keyword">(<span class="hljs-keyword">int i = ncount- <span class="hljs-number">1; i >= <span class="hljs-number">0; i--) {activity activity = Mactivitystack. <span class="hljs-keyword"> Get (i); Activity.finish (); } mactivitystack.clear (); Android.os.Process.killProcess (android.os.Process.myPid ()); }}</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></code></pre><p><p></p></p><p><p></p></p><p><p>This class can find similar source code in several clients of open source China.</p></p> <ul> <ul> <li><p><span class="__cf_email__" data-cfemail="397e504d79766a7a">[email protected]</span> in AppManager</p></li> <li><p>The AppManager in Android-app</p></li> </ul> </ul><p><p>The above two classes are the same, no difference.</p></p><p><p>The ubiquitous design pattern in Android Development--singleton mode</p></p></span>

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.