A single-instance pattern of Java Design Patterns essays

Source: Internet
Author: User

Java mode single-instance mode:

If you look at a single case pattern, you will see two classic structures:

    1. A Hungry man type
1  Public class Eagersingle {2  Private Static New Eagersingle ();   3   Public Static Eagersingle getinstance () {4return  instance;   5     }   6 }    

This is called a hungry man because the static variable instance is initialized directly when the class is loaded.

2. Lazy Type

1  Public classLazystringlet {2      Private StaticLazysingle instance =NULL; 3      /**4 * Static Factory method5         */   6PubliceStatic synchronizedLazysingle getinstance () {7          if(Instance = =NULL) {8Instance =NewLazysingle (); 9        }   Ten         returninstance; One     } A}
View Code

The lazy type is actually a kind of comparative image appellation. Now that you're lazy, you don't have to worry about creating an object instance. Will wait until the immediate use of the object instance will be created, lazy people, always can not shirk the time to actually do the work, so when loading the object does not create an object instance. (Excerpt from http://www.2cto.com/kf/201204/125917.html)

3. Two kinds of differences and advantages:

A hungry man, because the class is loaded when the instance is created, it will reduce the running time relatively;

Lazy, because of the getinstance () method to get the instance plus synchroized (lock) so it is thread-safe, so when the execution of multiple threads, it will be executed one at a time, so it is relatively slow on the run speed, but also because of the time when the thread enters the instance will be created , so it saves space.

Personal understanding: (temporary) singleton mode, only in the multi-threaded meaning, in the sequence structure of the program does not make much sense. There are not many opportunities for working with multi-threading, so this is not a very deep understanding.

A single-instance pattern of Java Design Patterns essays

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.